0

我正在尝试使用 getTime 为图片库设置计时器。当我在 imageWait() 的 else 块中添加警报时,此函数可以正常工作,但没有警报什么也不会发生。任何想法为什么?

milliseconds=null;
galleryLoop();

function galleryLoop(){
    date=new Date();
    startTime=date.getTime();
    milliseconds=5000;
    imageWait();    
}

function imageWait(){
    date=new Date();
    currentTime=date.getTime();
    if(startTime+milliseconds<=currentTime)
        alert('made it')
    else
        imageWait();
}
4

2 回答 2

0

你为什么不使用这个setTimeout功能呢?

function galleryLoop(){
    setTimeout(5000, imageWait());
}

function imageWait() {
    //Whatever you need to do
}
于 2014-01-15T04:59:12.100 回答
0

当您将 alert 语句添加到 else 子句时,这样做的原因是 alert 是一个阻塞调用,这意味着 JavaScript 执行会在创建警报窗口时停止。也就是说,当警报语句出现时,它允许挂钟时间增加(同样,随着时间的推移,没有 JS 执行)并且一旦警报被清除,if 语句最终会得到满足。这也意味着,如果您足够快地清除警报,您就有可能遇到与以前相同的问题。

通常发生的情况——没有警报语句——是 JS 引擎在 5000 毫秒延迟期间处理对 imageWait 的多次调用,并最终达到最大调用堆栈大小——如果你愿意的话,堆栈溢出——并抛出一个错误。

正确的解决方案是使用 setTimeout 延迟此功能:

var galleryTimeout = 0;

function galleryLoop(){
   //Process current image
   galleryTimeout = setTimeout(galleryLoop, 5000);
}

//Some time later, when done with the gallery
clearTimeout(galleryTimeout);
于 2014-01-15T06:54:38.373 回答