Fiddle here: http://jsfiddle.net/F6nJu/
I have a colored box:
#colorblock { background:#3ff; width: 100%; h
var arr = ["#f00", "#ff0", "#f0f", "#f66"];
// run through the array forever
(function recurse(counter) {
// get the colour
var color = arr[counter];
// animate it
$('#colorblock').delay('1200').animate({
backgroundColor: color
}, 600);
// delete the value to save memory
delete arr[counter];
// add the value at the end of the array
arr.push(color);
// run it again for the next number
setTimeout(function() {
recurse(counter + 1);
}, 200);
// start it for the first number.
})(0);
Infinite recursion. Delete the current entry, then add the current value to the end.
Live Example
For those who are interested in what the array looks like:
["#foo", "#ff0", "#f0f", "#f66"] (counter = 0)
[undefined, "#ff0", "#f0f", "#f66", "#foo"] (counter = 1)
[undefined, undefined, "#f0f", "#f66", "#foo", "#ff0"] (counter = 2)
[undefined, undefined, undefined, "#f66", "#foo", "#ff0", "#f0f"] (counter = 3)
[undefined, undefined, undefined, undefined, "#foo", "#ff0", "#f0f", "#f66"] (counter = 4)
etc.
var arr = ["#f00", "#ff0", "#f0f", "#f66"];
(function recurse(counter) {
var arrLength = arr.length;
var index = counter%arrLength;
var color = arr[index];
$('#colorblock').delay('1200').animate({
backgroundColor: color
}, 600);
setTimeout(function() {
recurse(counter + 1);
}, 200);
})(0);
Array.prototype.recurse = function(callback, delay) {
delay = delay || 200;
var self = this, idx = 0;
setInterval(function() {
callback(self[idx], idx);
idx = (idx+1 < self.length) ? idx+1 : 0;
}, delay);
}
Try it on StackOverFlow:
["#f00", "#ff0", "#f0f", "#f66"].recurse(function(item, index) {
$('body').css('background-color', item);
}, 300);
Try this:
var arr = ["#f00", "#ff0", "#f0f", "#f66"];
$.each(arr, function(key, value) {
set_color(value);
});
function set_color(color) {
$('#colorblock').delay('1200').animate({
backgroundColor: color
}, 600);
setTimeout(function() {
set_color(color);
}, 2000); //restart in 2 seconds
}
Fiddle: http://jsfiddle.net/maniator/F6nJu/1/