关于javascript:setTimeout(callback),而while循环永远不会触发

setTimeout(callback) followed by while loop never fires

我在下面有以下代码(请注意,稍后我将在循环中添加更多代码,但是我需要首先使用它):

1
2
3
4
5
6
7
8
9
10
11
var calls_on = true;
function hunt(max, ext, duration){
    if(duration != '0' || duration != false || duration != 0){
        duration = duration * 1000; // milliseconds to delay before stopping calls
        var t=setTimeout(function(){calls_on=false;}, duration);
    }
    while(calls_on){
        alert('reached');
    }
    ;
}

我已经确认" duration"条件正在执行,并且正在设置超时句柄。 但是,此循环永远不会结束,而且我也从未看到setTimeout回调得到执行。 当我完全删除循环时,它可以正常工作(因为这使它成为函数中唯一的代码)。

任何帮助,将不胜感激。 setTimeout是否超出范围? 循环如何使超时脱轨?


JavaScript是单线程的。 只要代码停留在循环中,超时就永远不会运行。

任何依赖于超时完成的事情都应该在超时之内。


从基于事件的编程中:异步具有什么同步功能

Interestingly, a timeout will not execute until all of the remaining
code in a block has executed. So if a timeout is set, and then some
long running function executes, the timeout will not even start until
that long running function has finished. In actuality, async functions
like setTimeout and setInterval are pushed onto an queue known as the
Event Loop

因此,由于后面有无限循环,因此永远不会执行setTimeout