techedryan February 2016

How to make my program run continously

I want to make my program run continously so that when it is done it will run again after 2 seconds.

Heres my code :

$(document).ready(function () {

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

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

Answers


Oliver Queen February 2016

I would sugget using setInterval() for this:

var myVar = setInterval(myTimer, 1000);

function myTimer() {
    var d = new Date();
    document.getElementById("demo").innerHTML = d.toLocaleTimeString();
}


charlietfl February 2016

You can have the function call itself when it gets to last change.

function colourBoard() {
    $.each(colorBlocks, function (i) {
        setTimeout(function() {
            $('#' + this).css("background", this);
            setTimeout(function() {
                $('#' + this).css("background", '#212121');

                // start over if it's the last one
                if(i === colorBlocks.length-1){
                   colourBoard();
                }


            }.bind(this), i * 200);
        }.bind(this), i * 500);
    });
}
colourBoard();

Pros: Using setInterval doesn't start getting ahead of the timers in function

Cons: Requires a bit more logic to pause/restart than using setInterval

Post Status

Asked in February 2016
Viewed 1,533 times
Voted 5
Answered 2 times

Search




Leave an answer