2016-03-15 145 views
0

我尝试每2秒输出一个带有消息“hello”的警告框,但只有5次。所以我写了这样的代码:setTimeout在做while while循环时

var counter = 1; 

do { 
    setTimeout 
    (
     function() 
     { 
      alert("hello"); 
      counter++; 
     }, 
     2000 
    ); 
} while(counter <= 5); 

但是我的页面每次都会崩溃?为什么? 在警报之间添加2000ms延迟的最佳方式是什么?

+0

的可能的复制[是否有可能在Javascript链setTimeout的功能是什么?(http://stackoverflow.com/问题/ 6921275/is-it-it-it-it-it-it-ita-set-out-functions-in-javascript) – smnbbrv

回答

4

但我的网页每次崩溃?为什么?

因为计数器只在回调中增加 - 循环可能会尝试在该时间内运行数千次(如果不是数万次)并且快速运行浏览器内存不足。更准确地说,正如在评论中指出的那样,循环永远不会放弃对调用的控制 - 所以这是永远不会运行的(不要担心这里的区别 - 只是接受你的计数器没有增加)

最新最好的方式来增加2000毫秒的延迟警报关闭之间仅与前一个完成下一个

踢。

function showHello(i){ 
    if(i<5){ 
    setTimeout 
    (
     function() 
     { 
      alert("hello"); 
      showHello(i+1) 
     }, 
     2000 
    ); 
    } 
} 

showHello(0); 

相关:Is it possible to chain setTimeout functions in Javascript?how to make a setInterval stop after some time or after a number of actions?

+2

“在那个时候” - 它从来没有达到过这一点。 JS事件循环忙于运行'while'来查看是否有定时器耗尽,所以它不会达到超时功能。 – Quentin

+0

实际上永远不会执行超时回调,因为循环永远不会放弃控制权。你可以将延迟设置为0,它仍然会崩溃。 –

+0

当然,你们都绝对准确。由于OP正在为这个概念而努力,我认为我们可以认为这只会混淆它们。我已经更新了答案 – Jamiec

0

使用的setInterval来代替:

var counter = 0; // setting the counter 
var interval = setInterval(function(){ //setInterval does repeatedly what setTimeout only 
             //does once 
    counter++; 
    if(counter === 5){ 
     clearInterval(interval); //if the counter reaches 5 (the times you asked 
           //for repeating the alert box) you clear the interval, 
           //stopping the loop 
    } 
    alert("hello"); 
}, 2000); 

这里的工作小提琴:https://jsfiddle.net/mwosm34x/

+3

这只回答问题的一部分,并没有提供解决方案的解释。 –

+1

@FelixKling对代码做了一些评论,希望现在能够更好地解释(我是新来的,在stackoverflow上回答,仍然需要完美的回答) –

0

使用setInterval代替。

而且clearInterval()当计数器大于5

var counter = 1; 
 

 
var timer = setInterval(function() { 
 
    alert("hello "+counter); 
 
    counter++; 
 
    if (counter > 5) { 
 
    clearInterval(timer); 
 
    } 
 
}, 2000);

+2

“试试这个”,没有解释代码,或者什么错误帮助没有人 – Jamiec