techedryan February 2016

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?

Answers


Medda86 February 2016

do a setInterval and increase the number every 2 seconds and call the function that shows your block.


mmm February 2016

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.


JazzCat February 2016

This should work

$(document).ready(function () {
    var colorBlocks = [
        'yellow',
        'green',
        'blue',
        'white',
        'orange'
    ];

    $.each(colorBlocks, function (index, key) {
          var selector = $("#" + key);
          setTimeout(function () {
               selector.css("background", key);
          }.bind(this), index * 2000);
    });
});

JSBin: https://jsbin.com/gilemuzade/1/edit

Post Status

Asked in February 2016
Viewed 1,875 times
Voted 4
Answered 3 times

Search




Leave an answer