Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
442 views
in Technique[技术] by (71.8m points)

javascript - 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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

56.9k users

...