qwerty
qwerty

Reputation: 45

In JavaScript how to add delay in loop

In JavaScript how can i add delay to JavaScript loop In this below code

snakeclass.prototype.start = function() {
    while(1){
        if(this.collision()){
            console.log("game over");
            break;
        }

        this.movesnake();

        // delay here by 300 miliseconds
    }
};

how can i use Set Timeout function here;

Upvotes: 3

Views: 2024

Answers (1)

Shawn31313
Shawn31313

Reputation: 6052

That doesn't work. Your browser is just going to freeze up if you do this:

while (1) {}

You can however use a setInterval.

snakeclass.prototype.start = function() {
    var interval;
    var doo = function () {
        if(this.collision()){
            console.log("game over");
            clearInterval(interval);
        }
        this.movesnake();
    }.bind(this); // bind this so it can be accessed again inside the function
    doo();
    timeout = setInterval(doo, 300);
};

Upvotes: 5

Related Questions