DEV Community

Nozibul Islam
Nozibul Islam

Posted on

Understand event loop in simple words!

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.

Top comments (0)