JavaScript
The JavaScript Event Loop: How Asynchronous Code Works
JavaScript is single-threaded, which means it can only do one thing at a time. So how does it handle fetching data from an API without freezing the entire browser? The answer is the Event Loop. It’s a concept that separates the JavaScript engine from the Web APIs provided by the browser. When you call setTimeout or fetch, those tasks are handed off to the Web API. The JS engine continues executing the rest of your synchronous code. When the asynchronous task is done, its callback is pushed onto a queue (the callback or task queue). The event loop constantly checks if the call stack is empty. If it is, it takes the first task from the queue and pushes it onto the stack to run. Understanding this explains why code after a setTimeout runs first, even if the timeout is 0ms. It also clarifies why heavy synchronous loops can make a UI unresponsive—they block the stack, preventing the event loop from rendering updates.
2,292
Views
165
Words
1 min read
Read Time
May 2025
Published