Is blocking JavaScript callbacks?

If I register a cumbersome callback function for an event listener and this event fires twice in a short period. Will the second callback block the first?

I tried this in a 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 a result, the second callback was executed immediately after the first.

So now I'm confused with the non-blocking asynchronous JavaScript module: which part was done asynchronously?

+3


source to share


1 answer


Javascript in the browser is single-threaded and works with an event queue. One event will finish before the next event is fired. Thus, if a second click occurs while the first is still being processed, the second click will be queued and will not work until the first code has been processed.

You can read more about this concept of an event queue here:

How does JavaScript handle AJAX responses in the background?




In your specific example, once your code starts running, it is all in sync. The loop while

runs to completion and blocks (if any other Javascript fails until it is executed).

There are asynchronous ways to schedule some code to run in the future (using setTimeout()

or setInterval()

) that will allow other code to run at the same time, but you are not using that mechanism.

+7


source







All Articles