DEV Community

abu-bakarr
abu-bakarr

Posted on

Javascript Event Loop

The event loop in JavaScript is in charge of managing asynchronous events such as closures, promises, and timers. The event loop continues indefinitely, scanning the event queue for new events and processing them one by one. This enables JavaScript to execute numerous jobs at the same time without interfering with the primary process.

Here's an illustration of how the JavaScript event loop works:

console.log('Starting'); // First to log

setTimeout(() => {
  console.log('First Timeout');  // Forth to log
}, 1000);

setTimeout(() => {
  console.log('Second Timeout');  // Third to log
}, 500);

console.log('Ending');  // Second to Log
Enter fullscreen mode Exit fullscreen mode

Running this code results in the following:

The result of the console.log('Starting') line is "Starting," and it is performed simultaneously.

There are two calls to setTimeout methods. When a certain period of time has elapsed, these methods submit a callback code to be performed. One response will run in this scenario after 1000 milliseconds (1 second), and the other after 500 milliseconds. (0.5 seconds).

The output of the console.log('Ending') line is "Ending," and it is performed synchronously.

As soon as the event cycle begins, it scans the event queue for any outstanding events.

The callback code for the second setTimeout function, which has a delay of 500 milliseconds, is the first event in the list. The result of this return function's execution is "Second Timeout."

The event loop keeps checking the event list to see if there are any outstanding events.

The callback method for the initial setTimeout function, which has a delay of 1000 milliseconds, is the next event in the list. The result of this return function's execution is "First Timeout."

The event loop keeps checking the event queue to see if there are any outstanding events, but when there are none, it ends.

Starting
Ending
Second Timeout
First Timeout
Enter fullscreen mode Exit fullscreen mode

As you can see, the callback functions of the setTimeout functions were performed in the order in which they were filed rather than the order in which they were invoked. This is because the event loop is in charge of controlling how asynchronous code is executed, ensuring that it proceeds in the right sequence and does not obstruct the main process.

Top comments (0)