js event loop and task queue

Foreword

A major feature of the JavaScript language is single-threaded, that is to say, the same time can only do one thing. So why not have JavaScript multiple threads do?

As a browser scripting language, JavaScript main purpose is to interact with the user, as well as operating DOM. This determines that it can only be a single-threaded, otherwise it will bring a very complex synchronization problems. For example, suppose JavaScript while there are two threads, one thread to add content on a DOM node, another thread to delete this node, then the browser which thread should prevail?

Event loop and task queue

Single-threaded means, all tasks need to line up, before the end of a mission, will perform a post-task. If a task takes a long time ago, a task after he had been waiting for

If the queue is because computationally intensive, CPU busy, they do well, but many times the CPU is idle, because the IO device (input and output devices) is very slow (such as Ajax operation reads data from the network), had waiting for the results come out, and then execute down.

Designers realized JavaScript language, then the main thread can regardless of IO devices, hangs in the waiting task, run the task at the back. IO device returns to wait until the results come back, the pending tasks to continue execution.

Synchronization tasks (synchronous): queued for execution on the main thread task, only the first task is finished, you can perform a task after;

Asynchronous tasks (asynchronous): do not enter the main thread, and enter the task "Task Queue" (task queue), only the "Task Queue" notify the main thread, an asynchronous tasks can be carried out, the task will enter the main thread.

When the main thread running, producing heap (heap) and stack (stack), the stack of code calls various external API, they are added to various events (click, load, done) in "Task Queue" in. As long as the stack of code is completed, go to the main thread will read "Task Queue", followed by the implementation of those events corresponding to the callback function.

Event Loop

console.log(1);
console.log(2);
setTimeout(function(){
    console.log(3);
})
setTimeout(function(){
    console.log(4);
})
console.log(5);

Output: 12534

It was first performed in the stack code 125. settimeout will be placed in the queue, the execution stack when finished, the task queue of the event will be added to the stack in order to perform, get 34

 

I did not get to know the place: this process is implemented js engine or browser underlying implementation? In the end the task queue is empty execution stack notification or inquiry? b station to re-look at the free English video!

Guess you like

Origin www.cnblogs.com/lian-dong/p/11991786.html