setTimeout(callback) 后跟 while 循环永远不会触发 [英] setTimeout(callback) followed by while loop never fires

查看:29
本文介绍了setTimeout(callback) 后跟 while 循环永远不会触发的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have the following code below (note, I'll be adding more code into the loop later, but I need this to work first):

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');
    }
    alert('test');
}

我已确认持续时间"条件正在执行,并且正在设置超时句柄.然而,这个循环永远不会结束,而且我从未看到 setTimeout 回调被执行.当我完全删除循环时,它工作正常(因为这使它成为函数中唯一的代码).

I have confirmed that the 'duration' conditional is executing, and the timeout handle is being set. However, this loop never ends, and I never see the setTimeout callback getting executed. When I remove the loop entirely, it works fine (since that makes it the only code in the function).

任何帮助将不胜感激.setTimeout 是否超出范围?循环如何破坏超时?

Any help would be appreciated. Is setTimeout somehow out of scope? How is the loop derailing the timeout?

推荐答案

来自 基于事件的编程:什么是异步的过度同步

有趣的是,直到所有剩余时间都不会执行超时块中的代码已执行.所以如果设置了超时,然后一些长时间运行的函数执行,超时甚至不会开始那个长时间运行的函数已经完成.实际上,异步函数像 setTimeout 和 setInterval 被推送到一个称为事件循环

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 永远不会执行.

So, since you have an infinite loop after it, your setTimeout is never executed.

这篇关于setTimeout(callback) 后跟 while 循环永远不会触发的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆