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

Categories

I have this function which waits for an asynchronous function to do its job and then returns.

function synchronous(){
    var notYet = true;

    setTimeout(function(){
        notYet = false;
    }, 1000);

    while(notYet)
        ;

    return "Done synchronously!";
}

console.log(synchronous());

Here the function synchronous stall using the while loop untill the callback of the asynchronous function (here setTimeout) get executed. But, the callback is never called (checked using an alert inside the callback), therefore, notYet will remain true and the function loop will go forever. So, why doesn't the callback get called after 1000 ms?

NOTE: I don't care how to make an asynchronous function into a synchronous one. My question is why the callback not getting called?

See Question&Answers more detail:os

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

1 Answer

The callback isn't getting called because the only thread that can call it is tied up doing your infinite loop.

In browsers, JavaScript runs on a single main UI thread (plus as many web workers as you want to create). That thread runs on a job queue: It picks up a job to do (for instance, processing a click), does the job, and then yields back to wait for the next job. You're blocking that one thread with the infinite loop. The timer schedules the callback in the job queue (probably, that's implementation-specific), but the thread never finishes the current job (the one that called your infinite loop) and so it never picks up that next job.

NodeJS also runs your code in a single thread and so does the same thing. (Not all environments do, but I'm not aware of any with setTimeout that don't schedule the timer callback on the same thread that requested it.)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...