Understanding JavaScript’s Event Loop: A Practical Example

I’ve been diving into JavaScript’s asynchronous behavior and here’s a simple example that shows how synchronous and asynchronous code interact: javascript

const displayMessages = () => { ????

console.log("Hi");????

setTimeout(() => { ??console.log("1")?}, 0);?

?Promise.resolve().then(() => { ??console.log("2")});????

setTimeout(() => { ???console.log("3")?}, 0);????

Promise.resolve().then(() => { ??console.log("4"); ????});

displayMessages();

}

Output: Hi 2 4 1 3

Explanation:

1?? console.log("Hi") is executed first (synchronous code).

2?? Promises (then) are part of the microtask queue, which is executed after the current code finishes, but before macrotasks like setTimeout.

  • So, 2 and 4 are logged next.

3?? setTimeout tasks are added to the macrotask queue, which is executed after the microtasks are completed.

  • Hence, 1 and 3 are logged last.

?? Macrotasks vs Microtasks:

  • Macrotasks include tasks like setTimeout, setInterval, and I/O events, which are handled after microtasks.
  • Microtasks (Promises, MutationObserver) take priority and are processed right after the currently executing script.

This demonstrates how JavaScript’s event loop manages both synchronous and asynchronous operations efficiently.

#JavaScript #WebDevelopment #EventLoop #AsynchronousProgramming #Macrotasks #Microtasks

要查看或添加评论,请登录

Talat Hussain的更多文章

社区洞察