在 JavaScript 中,我如何为 JavaScript 循环添加延迟 在下面的代码中
snakeclass.prototype.start = function() {
while(1){
if(this.collision()){
console.log("game over");
break;
}
this.movesnake();
// delay here by 300 miliseconds
}
};
我如何在这里使用设置超时功能;
最佳答案
那是行不通的。如果您这样做,您的浏览器将会死机:
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);
};
关于javascript - 在 JavaScript 中如何在循环中添加延迟,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17644255/