Search code examples
javascriptjquerydelay

Insert a delay between every .each


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?


Solution

  • You're creating an anonymous function and inside that function this has a different meaning (i.e., the window object).

    One solution is to cache this:

    var $this = $(this);
    setTimeout(function() { 
        var colors = ['blue', 'green'];
        var n = Math.floor(Math.random() * colors.length);
        var color = colors[n];
        $this.addClass(color);
    }, 500 + (i * 500));