简体   繁体   中英

setTimeout(callback) followed by while loop never fires

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

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).

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

JavaScript is single-threaded. As long as the code is stuck in the loop, the timeout will never run.

Anything that relies on the timeout being completed should be inside the timeout.

From Event-Based Programming: What Async Has Over Sync

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM