3

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?

3
  • can you post HTML as well
    – Thangaraja
    Feb 8, 2016 at 21:18
  • use a settimeout in your each loop. multiply the iteration by 2000 milliseconds (2 seconds). take action in the callback.
    – Travis J
    Feb 8, 2016 at 21:19
  • 1
    What you're looking for is setInterval() Feb 8, 2016 at 21:19

3 Answers 3

1

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.

9
  • 1
    This is what I would suggest doing as well.
    – Travis J
    Feb 8, 2016 at 21:24
  • 2
    it says I have to wait 6 minutes before i can accept your question
    – RyanM
    Feb 8, 2016 at 21:25
  • how would I get the function to run continously ?
    – RyanM
    Feb 8, 2016 at 22:03
  • What do you mean? To have it restart all the time? @techedryan
    – baao
    Feb 8, 2016 at 22:03
  • yeah to restart it so after it ends it re-runs again @Michael
    – RyanM
    Feb 8, 2016 at 22:05
0

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

-1

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.