JavaScript中如何在循环中添加延迟?

3
在 JavaScript 中,我如何给 JavaScript 循环添加延迟?
在下面的代码中:
snakeclass.prototype.start = function() {
    while(1){
        if(this.collision()){
            console.log("game over");
            break;
        }

        this.movesnake();

        // delay here by 300 miliseconds
    }
};

我该如何在此处使用Set Timeout函数?


你是指延迟整个 while 循环吗? - Shawn31313
https://dev59.com/x3VD5IYBdhLWcg3wTJvF - user2579943
可能是如何在JavaScript循环中添加延迟?的重复问题。 - Felix Kling
1个回答

5

那样是不行的。如果你这样做,你的浏览器就会冻结:

while (1) {}

但是你可以使用 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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接