DEV Community

Cover image for Why JavaScript Never Sleeps: An Easy Guide to the Event Loop
VAIBHAV RAI
VAIBHAV RAI

Posted on

Why JavaScript Never Sleeps: An Easy Guide to the Event Loop

JavaScript as a Single-Threaded Language: Briefly mention how JavaScript handles only one task at a time, but the Event Loop makes it seem otherwise

. How the Event Loop Works: The key steps in the Event Loop process

  • Stack: The call stack manages synchronous code.

  • Queue: The callback queue holds tasks waiting to be executed.

  • Loop: The Event Loop checks if the stack is empty before
    moving tasks from the queue to the stack.

Image description

Breakdown of the Workflow :

Initial Code Execution:

console.log('Hi');
$.get('url', function cb(data) {
  console.log(data);
});
console.log('JSConfEU');

Enter fullscreen mode Exit fullscreen mode
  • When this code starts executing, console.log('Hi') is added to the Call Stack, and "Hi" is printed in the Console.

Asynchronous Function Call ($.get):

  • Next, $.get('url', function cb(data) { ... }) is encountered. This function initiates an HTTP request to retrieve data from 'url'.

  • Instead of blocking the main thread, the request is sent to the Web APIs environment (often part of the browser).

  • The callback function (cb) is registered to execute once the HTTP request completes, but it's not executed immediately. The HTTP request continues to load in the Web APIs section, marked as XHR (XMLHttpRequest), which is typical for handling network requests.

Moving to the Next Synchronous Line:

  • javaScript moves on to the next line, console.log('JSConfEU'), which is added to the Call Stack. "JSConfEU" is then printed to the Console.

Event Loop and Task Queue:

  • After finishing all synchronous code, the Call Stack becomes empty, and JavaScript waits for any asynchronous tasks to complete.

  • Once the HTTP request completes, the callback function (cb) is moved from the Web APIs to the Task Queue.

  • The Event Loop continuously checks if the Call Stack is empty, and when it is, the Event Loop moves tasks from the Task Queue to the Call Stack

Callback Execution:

  • When the Event Loop places the callback function on the Call Stack, it executes console.log(data); within the callback function, printing the data received from the HTTP request to the Console.

Summary :

This flow demonstrates how the Event Loop handles asynchronous code
by:

  • Processing synchronous code immediately on the Call Stack.

  • Handling asynchronous tasks in the Web APIs and, once completed, moving them to the Task Queue.

  • Allowing the Event Loop to move tasks to the Call Stack only when it's empty, ensuring non-blocking code execution.

Top comments (0)