Skip to content
Advertisement

How is the event loop never blocking but messages in the queue are run to completion?

I was learning about JavaScript’s event loop on the MDN doc. It mentioned that a message in the queue is run to completion, but at the end, it said that the event loop is never blocked. I don’t really understand this. Isn’t this a contradiction? Please help me understand the difference between them.

“Run-to-completion”

Each message is processed completely before any other message is processed. This offers some nice properties when reasoning about your program, including the fact that whenever a function runs, it cannot be pre-empted and will run entirely before any other code runs (and can modify data the function manipulates). This differs from C, for instance, where if a function runs in a thread, it may be stopped at any point by the runtime system to run some other code in another thread.

A downside of this model is that if a message takes too long to complete, the web application is unable to process user interactions like click or scroll. The browser mitigates this with the “a script is taking too long to run” dialog. A good practice to follow is to make message processing short and if possible cut down one message into several messages.

Never blocking

A very interesting property of the event loop model is that JavaScript, unlike a lot of other languages, never blocks. Handling I/O is typically performed via events and callbacks, so when the application is waiting for an IndexedDB query to return or an XHR request to return, it can still process other things like user input.

Advertisement

Answer

You’re right, the two citations contradict each other.

In the event loop, all messages are run-to-completion, as it is written in the first text, therefore they do block the event loop while they execute.

This is why timer2 won’t execute before the loop in timer1 finishes in this example:

console.log('start');

setTimeout(() => {
  const startTime = Date.now()
  while(Date.now() - startTime < 3000);
  console.log('timer1 end');
}, 0)
setTimeout(() =>  console.log('timer2'), 0);

/*
start
-- three seconds later --
timer1 end
timer2
*/

The text saying “never blocks” is supposed to mean that, unlike many languages, most APIs that take long (or are polling something slow) are designed to not block the event loop for a long time, instead, instruct the JS runtime to handle the task in a background thread without blocking JavaScript, and pass back the results to JS when they’re ready.

A much more accurate description of this would be that “although the event loop can be blocked by long-running code, most JS APIs are designed to avoid doing that”.

User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement