Event Loop in Javascript with examples

Understanding the Event Loop is crucial to mastering asynchronous programming in JavaScript, and in this article, we will take a closer look at how the Event Loop works internally and bring to the forefront its pivotal role in JavaScript's single-threaded, non-blocking I/O model.

Understanding JavaScript's Single-Threaded Nature

JavaScript is a single-threaded language. This means that it can only handle one task at a time. When there's a new task, JavaScript adds it to a queue called the call stack. The JavaScript engine will fetch tasks from the call stack, execute them, and remove them when they're done.

// this will be added to Call main stack and executed immediately
console.log("JavaScript!");

Diving into asynchronous operations

For operations that take a while (such as API calls, timeouts, or event listeners), JavaScript uses something called Web APIs (provided by the browser). When these long-running operations are performed, they move to the Web API, freeing up the call stack for other tasks.

setTimeout(() => {
  console.log("This is an example of asynchronous operation");
}, 2000);

Unraveling the role of the event loop

An event loop takes completed tasks from web APIs and puts them back into the call stack. This is where the magic happens, creating the illusion of multi-threading in a single-threaded environment!

// Simulating Event Loop
console.log("This is task 0"); // run immediately in 'main stack'

// setTimeout ~= put this into 2nd stack which will wait for the end of the main stack first
setTimeout(() => {
  console.log("This is task 1");
}, 0);
setTimeout(() => {
  console.log("This is task 2");
}, 0);
setTimeout(() => {
  console.log("This is a task with waiting 100ms");
}, 100);
setTimeout(() => {
  console.log("This is task 3");
}, 0);

console.log("This is task 4"); // run immediately

// Output:
// This is task 0
// This is task 4
// This is task 1
// This is task 2
// This is task 3
// This is a task with waiting 100ms

Summary

The event loop plays a critical role in JavaScript's single-threaded environment, allowing it to mimic multi-threaded behavior. Using web APIs and the call stack, JavaScript can perform tasks in a non-blocking manner, providing a smoother user experience.

Happy event looping!