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
source share