I've found a few other questions pertaining to this, but the answers didn't work for me, so I'm checking to see if there's anything newer or something that will work. Essentially, I'm updating divs in a .each in jQuery, but I want them to update a couple seconds apart. Here's what I've tried:
function randomColor() {
$('div').each(function(i) {
setTimeout(function() {
var colors = ['blue', 'green'];
var n = Math.floor(Math.random() * colors.length);
var color = colors[n];
$(this).addClass(color);
}, 500 + (i * 500));
});
}
I've also tried using a separate function:
function randomColor() {
$('div').each(function(i) {
var time = 500;
setTimeout(function() {
applyColor($(this));
}, time);
time += 500;
});
}
function applyColor(div) {
var colors = ['blue', 'green'];
var n = Math.floor(Math.random() * colors.length);
var color = colors[n];
$(div).addClass(color);
}
Both of these return no errors, but the divs don't get updated. If I run this code without the setTimeout, it works perfectly. I've also tried using delay in this fashion:
$('div').delay(1000).each(function() {
...
});
And that delayed by 1 second, but then updated everything at once after that second. If I move the delay down near the addClass line, it stops working altogether again. Can anyone point out this (hopefully simple) mistake?