Browser environment
The following two pieces of code are equivalent. Req The callback setting for the event, which is actually the task of the current main thread task queue.
var req = new XMLHttpRequest (); Req.open ( ' GET ' = function () {}; Req.onerror = function () {}; Req.send (); // equal var req = new XMLHttpRequest (); Req.open ( ' GET ' = function () {}; Req.onerror = function () {};
SetTimeout (fn,0): Adds a message to the end of the message queue, specifying that the main thread is empty (all synchronization tasks are executed) and that the FN function is executed as soon as possible
This should be understood for the event loop:
There is one (synchronous) task queue in the main thread and another message queue in the other.
Only when the task queue is empty, the main thread checks the message queue, takes the message, and then inserts the corresponding callback function into the task queue of the main thread as a task.
When the task queue is not empty, the main thread will continue to remove the task from the task queue and execute. Until the task queue is empty, this process is called an event loop
The event loop is actually the process of "performing tasks" and "fetching messages, inserting tasks" in the main thread, and the two parts keep looping
The only thing that can be seen in the main thread is to perform tasks, take messages, and insert tasks. So who's going to do this process of inserting messages?
The introduction of a concept here is called "worker thread", when the main thread executes a task, it may turn on an asynchronous task (such as ajax,timeout, etc.), which is actually to inform a worker to execute the asynchronous task, after the execution is completed, the worker thread will insert a message into the message queue, indicating the main thread of the notification I've done the job you gave me.
Node environment
Process.nexttick: Adds a task to the end of the synchronization task queue on the main thread, which means that the task executes before all callback functions
Setimmediate: Similar to settimeout (fn,0)
Visible:
Process.nexttick and setimmediate are significantly more efficient than the latter, since the former runs in the current event loop and does not need to check the message queue
JS Event loop