在JavaScript中如何在循环中添加延迟
在JavaScript中,如何向JavaScript循环添加延迟 在下面的代码中在JavaScript中如何在循环中添加延迟,javascript,loops,time,delay,Javascript,Loops,Time,Delay,在JavaScript中,如何向JavaScript循环添加延迟 在下面的代码中 snakeclass.prototype.start = function() { while(1){ if(this.collision()){ console.log("game over"); break; } this.movesnake(); // delay here by 300
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);
};
你的意思是,延迟整个while循环?可能重复的Hmm,尝试刷新页面。