2013-07-14 46 views
3

增加延迟在JavaScript中如何添加延迟到JavaScript的循环 在这下面的代码在JavaScript中如何循环

snakeclass.prototype.start = function() { 
    while(1){ 
     if(this.collision()){ 
      console.log("game over"); 
      break; 
     } 

     this.movesnake(); 

     // delay here by 300 miliseconds 
    } 
}; 

我怎样才能在这里使用设置超时功能;

+0

你的意思是延迟整个while循环吗? – Shawn31313

+0

@ Shawn31313 yess – qwerty

+0

http://stackoverflow.com/questions/24849/is-there-some-way-to-introduce-a-delay-in-javascript – 2013-07-14 22:06:19

回答

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); 
}; 
+0

投票不起作用 – qwerty

+0

嗯,请尝试刷新页面。 – Shawn31313

+0

没有足够的代表 感谢您的回答 – qwerty