Understanding JavaScript Event Loop

Imagine the below piece of JS code, what will the user experience? Hint: Answer lies in the understanding of the Event loop. #javascript

  • graphical user interface, text

Answer: JS is single-threaded so it relies on the event loop for handling concurrency without blocking the main thread. It has 3 parts - the call stack, the macrotask queue and the microtask queue. Micro tasks take the highest priority because they are interpreted as small and easy tasks so the event loop drains the micro task queue before yielding back to the browser for rendering. In the above function, each microtask schedules another microtask, and the queue never empties. This creates an infinite chain of microtasks. Since the event loop must fully drain the microtask queue before rendering, the browser never gets a chance to paint the UI and it appears frozen to the user.

To view or add a comment, sign in

Explore content categories