Understand event loop in simple words!
Nozibul Islam

Nozibul Islam @nozibul_islam_113b1d5334f

About: I am a Full-Stack Developer specialized Front-end Developer. Passionate about algorithms, data structures, and coding challenges & always ready to face new challenges.

Location:
Dhaka, Bangladesh
Joined:
Aug 24, 2024

Understand event loop in simple words!

Publish Date: Jan 7
40 2

Understand event loop in simple words!

🌻 𝗦𝗶𝗻𝗴𝗹𝗲-𝗧𝗵𝗿𝗲𝗮𝗱𝗲𝗱 𝗘𝘅𝗲𝗰𝘂𝘁𝗶𝗼𝗻:

  • JavaScript operates in a single-threaded environment, meaning it processes one thing at a time.
  • But thanks to the event loop, it doesn't get stuck waiting on things like user input or timers.

🌻𝗖𝗮𝗹𝗹𝗯𝗮𝗰𝗸 𝗤𝘂𝗲𝘂𝗲:

  • When asynchronous operations (like setTimeout or fetch requests) complete, their associated callback functions don’t execute immediately.
  • Instead, they get placed into a callback queue, where they’ll wait for their turn.

🌻𝗪𝗲𝗯 𝗔𝗣𝗜𝘀:
-JavaScript hands off certain tasks, like network requests or timers to Web APIs (provided by the browser).
-These APIs process tasks outside the main JavaScript thread, allowing the main thread to keep running while waiting for these operations to finish.

🌻𝗠𝗶𝗰𝗿𝗼𝘁𝗮𝘀𝗸𝘀 𝗤𝘂𝗲𝘂𝗲:

  • Aside from the callback queue, there’s also the microtasks queue, which holds tasks with higher priority, such as promises that have been resolved.
  • Microtasks must be executed before anything in the callback queue.

🌻𝗘𝘃𝗲𝗻𝘁 𝗟𝗼𝗼𝗽'𝘀 𝗥𝗼𝗹𝗲:

  • The event loop is like a coordinator. It continuously checks whether the call stack is clear. Once it’s empty, it first looks at the microtasks queue, ensuring that high priority tasks are handled first. Only after the microtasks queue is empty does it start picking tasks from the callback queue.

🌻𝗖𝗮𝗹𝗹 𝗦𝘁𝗮𝗰𝗸:

  • The call stack is where the magic happens. It holds the functions that are currently being executed. Functions are added to the stack when they’re called and removed once they’ve been completed.
  • If the call stack is busy, the event loop will wait for it to be free.

🌻𝗛𝗼𝘄 𝗜𝘁 𝗔𝗹𝗹 𝗪𝗼𝗿𝗸𝘀 𝗧𝗼𝗴𝗲𝘁𝗵𝗲𝗿:

  • To summarize the process: the event loop keeps the call stack clear by processing microtasks first, then moving on to the callback queue.
  • This allows JavaScript to handle asynchronous code efficiently while maintaining responsiveness.

⭐ The event loop lets JavaScript perform non-blocking operations, ensuring tasks are executed in the right order without blocking the main thread.

Comments 2 total

Add comment