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;

qwerty
  • 45
  • 5

1 Answers1

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);
};
Shawn31313
  • 5,978
  • 4
  • 38
  • 80