setTimeout(callback)跟随while循环从不触发 [英] setTimeout(callback) followed by while loop never fires

查看:227
本文介绍了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');
}



我已经确认'duration'条件正在执行,正在设置。然而,这个循环永远不会结束,我从来没有看到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天全站免登陆