Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is JavaScript callbacks blocking?

If I registered a time-consuming callback function to an event listener, and this event is fired twice in a short period. Will the second callback be blocked by the first one?

I tried this in browser:

document.body.onclick = function() {
    var date = new Date;
    console.log('click event at ' + date);

    while(new Date - date < 1e4) {};

    console.log('callback end');
}

As the result, the second callback was executed right after the first one is done.

So now I am confusing with the JavaScript non-blocking async module: which part has been executed asynchronously?

like image 431
Dolphin_Wood Avatar asked Apr 18 '15 06:04

Dolphin_Wood


1 Answers

Javascript in a browser is single threaded and works off an event queue. One event will run to completion before the next event is triggered. So, if a second click occurs while the first is still processing, the second click will be queued and will not run until the code processing the first one is done.

You can read more about this event queue concept here:

How does JavaScript handle AJAX responses in the background?


In your particular example, once your code starts running, it is all synchronous. The while loop runs until completion and is blocking (keeping any other Javascript from running until it is done).

There are asynchronous ways to schedule some code to run in the future (using setTimeout() or setInterval()) that would allow other code to run in the meantime, but you aren't using that mechanism.

like image 86
jfriend00 Avatar answered Oct 18 '22 20:10

jfriend00