Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

setTimeout() in for each loop doesn't work

I have to make a board as an assignment which lights up 1 by 1 like the sci-fi movie “Close Encounters of the Third Kind”. The main objective here is to get specific blocks to light up in a specific order with 2 second interval between them this is the code I have done now:

$(document).ready(function () {

    var colorBlocks = [
        'yellow',
        'green',
        'blue',
        'white',
        'orange'
    ]

    $.each(colorBlocks, function (i) {
        $('#' + this).css("background", this);
        // When you use the alert you can see the boxes change color one by one
        // alert(something);
    });

});

but this doesn't seem to work it changes the colour of all the boxes at once unless if you alert(something);

can anyone help?

like image 485
RyanM Avatar asked Aug 03 '26 19:08

RyanM


1 Answers

I think you want something like this:

$.each(colorBlocks, function (i) {
    setTimeout(function() {
        $('#' + this).css("background", this);
    }.bind(this), i * 2000);
});

Why i * 2000?

i is the iteration's index, so it'll wait i * 2000 ms for each call for the next "animation" to occur.

like image 121
baao Avatar answered Aug 05 '26 08:08

baao



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!