How to use setInterval in a slightly irregular pattern, for example, in a for loop?

The behavior I want is the following: The background color changes, say, gold, and remains the color that X speaks of duration. Then the background color changes, say, red, and remains the same color as for Y-time. Then the background color returns to gold and remains the same color as for X duration. Then the background color changes to red and stays that way for the Y length of time. All this kit and caboodle is done in a loop style for Z number of times and then ends.

I tried putting the setInterval'd functions in a for loop (to count the number of changes we made), but found that all the functions that were set for setInterval all started to run interval timers at the same time (not in sequence).

Hope this is clear. Here is the JSFiddle of my efforts: http://jsfiddle.net/6WE6s/3/ I managed to change the background color in an even pattern, but I want the one described above and I'm confused about what to do next.

Thank you in advance for your help! :)

+4
source share
7 answers
var colors = [ ['gold', 2000], // X = 2000 miliseconds ['red', 1000] // Y = 1000 ], repeat = 3, // Z = 3, index = 0, // current position in colors array changeColor = function( ) { // if index == colors.length then mod = 0 var mod = index % colors.length; if(!index || mod || --repeat ) { index = mod; var data = colors[ index++ ]; // data = [ currentColor, currentColorTimeout ] document.body.style.background = data[0]; setTimeout( changeColor, data[1] ); // and so on } //if index >0 && index == last //then decrement `repeat` and check if is == 0 //nothing to do :) }; changeColor(); // run 

This is a simple example. You can use the function with arguments ( colors , repeats ) and its body, as described above.

Note: setInterval not suitable for this purpose, because in setInterval you will skip the timeout once

If repeat initially 0, there will be an infinite number of repetitions

+2
source

Do not use setInterval() . With setTimeout() you can do something like this:

 function changeColors(colors, repeats) { var i = 0; if (typeof repeats === "undefined") repeats = 1; function doNext() { if (i >= colors.length){ if (--repeats > 0) i = 0; else return; } $('body').css('background-color', colors[i].color); setTimeout(doNext, colors[i++].delay); } doNext(); } changeColors([{color : "gold", delay : 2000}, {color : "red", delay : 4000}], 3); 

You can add as many colors as you want, each with its own delay, by adding more elements to the array that you pass to changeColors() . The function will go through the colors in turn, and make the entire sequence the number of times specified in the repeats parameter.

Demo: http://jsfiddle.net/nnnnnn/6WE6s/10/

+1
source

Here's my effort - no jQuery required:

 function colorCycle(el, count, cols) { var i = 0, n = cols.length; // allow this to work on any element given its ID el = (typeof el === "string") ? document.getElementById(el) : el; if (n === 0) { return; // no colours? } else if (n === 1) { count = 1; // don't trigger any timers if there only one colour } // all of the hard work is done here (function repeat() { var interval = cols[i][1]; el.style.backgroundColor = cols[i][0]; // only do the whole cycle "count" times - 0 = forever if (++i === n) { if (count && !--count) { return; } i = 0; } setTimeout(repeat, interval); // call myself })(); // IIFE starts the cycle straight away }; colorCycle(document.body, 5, [ ['red', 1000], ['gold', 500]]); 

See http://jsfiddle.net/alnitak/42PeT/

+1
source

try it

 var colors = []; colors.push({color:"gold", time:4000}); //4000 X length of time colors.push({color:"red", time:2000}); //2000 Y length of time var numberofTimes = 50; //50 Z number of times var $body; var times = 0; // counter for tracking var currentColor = {}; //currentColor info can be used to get the current $(function(){ $body = $('body'); changeBG(); }); function changeBG() { currentColor = colors[times % colors.length]; $body.css('background-color',currentColor.color); times++; if(times<numberofTimes) setTimeout(changeBG, currentColor.time); } 

check out this quick demo

0
source

Refrain from using setInterval. Link here .

EDIT . I missed a different call delay.

 var colors = ["#FF0000", "#00FF00", "#0000FF"]; var times = [1000, 2000, 3000]; var backgroundColor = ""; var counter = 0; var changeBackground = function () { // if we ran out of colors — do nothing: this simply goes out // of the function, without continually calling setTimeout. if (counter >= colors.length) return; // you fetch your new color here and increase the counter // The counter keeps count of how many animations you've done. backgroundColor = colors[counter]; // increase the counter to point to the next index of colors // array you'll use in a subsequent call counter++; // do your magic voodoo change background animation here. // I'm just doing a console.log() to be sure this works. // Your question was framework agnostic, the answer should be too. console.log(backgroundColor); // setInterval to repeat window.setTimeout(changeBackground, times[counter]); } window.setTimeout(changeBackground, times[counter]); 
0
source

Basic example repeating an array of color and temporary arrays with setTimeout .

 (function() { var i = 0, colorsTimes = [['gold', 'red', 'gold', 'red', 'gold'], [2000, 4000, 2000, 4000, 2000]]; function switchColors() { setTimeout(function() { $('body').css('background-color', colorsTimes[0][i]); if (++i < colorsTimes[0].length) switchColors(); }, colorsTimes[1][i]); } switchColors(); }()); 

Fiddle

0
source

Using setTimeout:

 var doCount = (function() { var count = 0; var interval; var limit = 5; // default return function(num) { limit = num || limit; if (count < limit) { count++; console.log('running number ' + count); interval = setTimeout(arguments.callee, 1000); } else { interval && clearTimeout(interval); } } }()) 

Using setInterval:

 var doCount = (function() { var count = 0; var interval; var limit = 5; // default return function(num) { limit = num || limit; if (interval) { if (++count >= limit) { interval && clearInterval(interval); } console.log('running number ' + count); } else { interval = setInterval(arguments.callee, 1000); } } }()) 

The advantage of setTimeout is that you can adjust the time between runs to make it more regular, setInterval just tries to work as often as possible.

-1
source

Source: https://habr.com/ru/post/1432871/


All Articles