Event Loop: The Central Understanding of Asynchronous Programs

The event loop is a mechanism that manages the execution of asynchronous code in most modern web browsers and JavaScript environments. It controls the flow of code execution, handling events, invoking callback functions, and managing other asynchronous tasks, allowing programs to efficiently process asynchronous tasks.

Key Elements of the Event Loop

JavaScript operates as a single-threaded language, meaning it can execute only one task at a time. Therefore, when I/O operations such as network requests, file reading, or user input occur, the program needs to continue processing other tasks without waiting. The event loop is used to effectively handle such asynchronous tasks.

  • Call Stack: A stack that stores information about currently executing functions. When a function is called, its information is added to the stack, and when the function returns, it is removed from the stack.

  • Callback Queue: A queue where callback functions of asynchronous tasks wait. When an asynchronous task is completed, its corresponding callback function is added to the callback queue.

  • Event Loop: Monitors the call stack and callback queue. It moves callback functions from the callback queue to the call stack only when the call stack is empty.

Let's look at the execution result of a program:

  1. Start
  2. End
  3. Completion of asynchronous function
  4. Execution of callback function

When the program starts, 'Start' is the first output. Then, the asyncFunction is an asynchronous function that completes its task after a 2-second delay using the setTimeout function and calls the callback function. However, the program continues executing without waiting for the callback function. 'End' is output. After waiting for 2 seconds, asyncFunction is executed. After 2 seconds, the setTimeout callback function is executed, outputting 'Completion of asynchronous function.'' Finally, the content defined in the setTimeout callback function is executed, outputting 'Execution of callback function.'

Event Loop

function asyncFunction(callback) {
    setTimeout(function() {
        console.log("Completion of asynchronous function");
        callback(); 
    }, 2000);
}

console.log("Start");

asyncFunction(function() {
    console.log("Execution of callback function");
});

console.log("End");


The Operation Process of the Event Loop

  1. Execution of the code begins, and initial function calls are added to the stack.
  2. Asynchronous tasks occur, and these tasks are processed in the background.
  3. Upon completion of asynchronous tasks, callback functions are added to the callback queue.
  4. The event loop continuously checks whether the call stack is empty. If it is, the event loop retrieves callback functions from the callback queue and adds them to the call stack.
  5. When functions added to the call stack are executed, asynchronous tasks may occur, and this process is repeated.