What is the JavaScript Event Loop?
In JavaScript, an event loop is a mechanism that controls the execution of code, events, or messages using non-blocking I/O. This provides a way for non-blocking, or asynchronous, operations in JavaScript.
1.Single Threaded
JavaScript is single-threaded, which means it executes one task at a time. Single threaded, therefore, one thread on which JavaScript executes is the so-called "main thread.
2.Call Stack
It is the data structure in which JavaScript keeps track of function calls. A function call is pushed onto the stack. When it returns, it is removed. When it is empty, JavaScript is ready to process the next thing. It is also commonly referred to as the "main thread".
3.Heap
This is where JavaScript stores objects and variables. It's used for dynamic memory allocation.
4.Event Queue
A queue of messages or tasks that are waiting to get executed. When a task is added into the queue, it waits for the call stack to be empty to execute.
5.Event Loop
It is something that constantly monitors the call stack and event queue. If the call stack is empty, it then moves tasks from the event queue into the call stack and executes them.
Process
Callback Functions: When an asynchronous operation completes, its callback function is pushed into the event queue.
Event Loop Checking: Event Loop now checks the call stack as well as the event queue in the order. If the call stack is empty, it picks the first task from the event queue and pushes that into the call stack to run it.
console.log('Start'); setTimeout(() => { console.log('Timeout 1'); }, 1000); setTimeout(() => { console.log('Timeout 2'); }, 500); console.log('End');
Note that the following will occur step-by-step:
Summary
The above is the detailed content of JavaScript Event Loop. For more information, please follow other related articles on the PHP Chinese website!