JavaScript - What is Event Loop?

It is known that JavaScript is single threaded. It runs usually in browser which must remain responsive all the time. If a code which could run slow and is written synchronously, the main thread gets blocked and UI becomes unresponsive. It’s a huge problem!

Event loop solves this problem by allowing to queue functions to be executed later when there is nothing to be executed on main thread.

Take the following code as an example. Everything is running synchronously.

console.log('Fast! But not everyone.');
await slowCode(2000);
console.log('I was blocked by slow code.');

Slow code emulator.

const delayForMs = (forMilliseconds) 
        => new Promise(resp 
            => setTimeout(resp, forMilliseconds));
async function slowCode(forMilliseconds) {
    console.log('I block browser.');
    await delayForMs(forMilliseconds);
    console.log('Finally I am done!');
}

What gets printed on console on execution

Fast! But not everyone.
I block browser.

Nothing happens for next 2 seconds, then below gets printed.

Finally I am done!!
I was blocked by slow code.

Now take slightly modified code where some part of the code goes to event loop.

console.log('Fast! But not everyone.');
setTimeout(async () => {
    // This would be queued in event loop
    await slowCode(2000);
}, 0);
console.log('I\'m not blocked anymore.');

Executing above code would give the following output. It can be seen that once everything is executed and when main thread is free, then the function from event loop executes.

Fast! But not everyone.
I'm not blocked anymore.
I block browser.

Nothing happens for next 2 seconds, then below gets printed. But this time slow code executes when main thread is free.

Finally I am done!!

There is a great video by Philip Roberts on YouTube explaining Event loop Event Loop Simplified

Comments

Post a Comment