Skip to main content

JavaScript Event Loop (Live Playground)

JavaScript is single-threaded, meaning it can only execute one task at a time. However, it has a powerful concurrency model based on the event loop, which allows it to handle multiple tasks simultaneously without blocking the main thread. This tutorial will introduce the event loop and explain how JavaScript's concurrency model works.

JavaScript's Single-Threaded Nature

JavaScript runs on a single thread, which means it can only execute one operation at a time. To handle multiple tasks without blocking the main thread, JavaScript uses an event-driven, non-blocking I/O model.

Example:

console.log('Start');

setTimeout(function () {
console.log('Async operation');
}, 1000);

console.log('End');

In this example, the setTimeout function schedules an asynchronous operation to be executed after a delay of 1000 milliseconds. The main thread is not blocked, and the program continues executing the next statement, logging "End" to the console.

Live Playground, Try it Yourself

The Event Loop

The event loop is a continuous process that allows JavaScript to handle asynchronous tasks by cycling through a queue of tasks and executing them one at a time. The event loop consists of the following steps:

  • Check the task queue: If there are tasks in the queue, execute the next task.
  • Check the microtask queue: If there are microtasks (e.g., promises) in the queue, execute them before moving on to the next task.
  • Execute any necessary rendering updates.
  • Repeat.

Example:

console.log('Start');

setTimeout(function () {
console.log('Timeout callback');
}, 0);

Promise.resolve().then(function () {
console.log('Promise callback');
});

console.log('End');

In this example, the event loop executes the tasks in the following order: log "Start," log "End," execute the promise callback, and then execute the timeout callback.

Live Playground, Try it Yourself

Asynchronous Code Execution

The event loop enables JavaScript to execute asynchronous code without blocking the main thread. As a result, JavaScript can handle tasks such as network requests, timers, and user interactions efficiently and responsively.

Example:

function fetchData() {
return new Promise(resolve => {
setTimeout(() => {
resolve('Data fetched');
}, 2000);
});
}

console.log('Fetching data...');

fetchData().then(data => {
console.log(data);
});

console.log('Doing other tasks...');

In this example, the fetchData function simulates an asynchronous data fetch using a promise. The main thread continues executing other tasks while waiting for the data fetch to complete.

Live Playground, Try it Yourself

Conclusion

Understanding JavaScript's event loop and concurrency model is crucial for writing efficient, non-blocking code. By leveraging the event loop, you can create highly responsive applications that handle multiple tasks simultaneously without blocking the main thread.