JavaScript runs on a single thread, which means it can only do one thing at a time.
So how does it still handle things like timers, network requests, and promises without getting โstuckโ?
๐ Thatโs where the event loop comes in.
Itโs the system that makes JavaScript look asynchronous even though it runs in one thread.
Letโs break it down.
Key Parts of the Event Loop
The Rules of the Event Loop
So, microtasks always โcut in lineโ before macrotasks.
Examples
Case 1
function foo() {console.log(1)}console.log(2)foo()
// Expected Output// 2// 1
Lets see how the Event Loop handles
Case 2
function foo() {console.log(1)}console.log(2)setTimeout(() => {console.log(3) // schedule a macrotask}, 0)foo()
// Expected Output// 2// 1// 3
Case 3
function foo() {console.log(1)}console.log(2)setTimeout(() => {console.log(3) // schedule a macrotask}, 0)Promise.resolve().then(() => {console.log(4) // schedule a microtask})foo()
// Expected Output// 2// 1// 4// 3
Case 4
setTimeout(() => {console.log("timeout 1");// Schedule a microtask inside the macrotaskPromise.resolve().then(() => {console.log("microtask 1");// Schedule ANOTHER macrotasksetTimeout(() => {console.log("timeout 2");}, 0);});}, 0);setTimeout(() => {console.log("timeout 3");}, 0);console.log(1)
// Expected Output// 1// "timeout 1"// "microtask 1"// "timeout 3"// "timeout 2"
Case 5
Any code within the then, catch and finally or any code after await in the code block is scheduled as a microtask
console.log("start");Promise.resolve().then(() => {console.log("then 1");}).then(() => {console.log("then 2");});console.log("end");
// Expected Output// start// end// then 1// then 2
async function run() {console.log("start");await Promise.resolve();console.log("then 1");await Promise.resolve();console.log("then 2");}run();console.log("end");
// Expected Output// start// end// then 1// then 2
Summary
The JavaScript Event Loop is a mechanism that allows JavaScript to perform non-blocking operations despite being single-threaded. Here's what we've learned:
Understanding the Event Loop is crucial for predicting code execution order in JavaScript and avoiding common asynchronous programming pitfalls.