3

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;

3

1 Answer 1

5

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);
};
Sign up to request clarification or add additional context in comments.

1 Comment

Hmm, try refreshing the page.

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.