current position:Home>Understand the timer and JS execution mechanism

Understand the timer and JS execution mechanism

2021-08-27 04:59:24 LBJ

This is my participation 8 The fourth of the yuegengwen challenge 22 God , Check out the activity details :8 Yuegengwen challenge

There is no foreword , Go straight in , Let's talk about timers !

We know , Timer setInterval and setTimeout Is defined in window Two functions on

image.png

These two functions take two arguments :

  1. The first parameter : Accept a callback function callback
  2. The second parameter : Indicates the number of milliseconds delayed execution . time
// every other 100 One output in milliseconds 1
setInterval(function(){
  console.log(1);
},100);
//100 Output in milliseconds 1, Output only once 
setTimeout(function(){
  console.log(1);
},100);
 Copy code 

The difference is :

  1. setTimeout Indicates a timer , Executes the callback function after the specified number of milliseconds , Only once ; and setInterval Indicates a timing circulator , The callback function is executed every specified number of milliseconds , If the timer is not cleared , The callback function will execute countless times
  2. When the timer is cleared ,setInterval Corresponding clearInterval(),setTimeout Corresponding clearTimeout()

clearInterval and clearTimeout It is also defined in window The function on , Accept a parameter to represent the name of the timer , Clear the corresponding timer according to this name

When using the timer, pay attention to several points :

1. If there is no name when creating the timer , The timer cannot be cleared ;

2. Timers are defined in global objects window On , Internal function this Point to the window;

3. setInterval The number of milliseconds passed in it will only be recognized the first time , You can't change it later

4. setTimeout, setInterval It's an asynchronous task

Some students may not know what asynchronous tasks are ?

In fact, we should have an in-depth understanding of asynchronous , You have to understand js Implementation mechanism of

Let's start with an example

// What is the execution result of the following code 
var p = new Promise(resolve => {
    console.log(4);
    resolve(5);
});
function func1() {
    console.log(1)
}
function func2() {
    setTimeout(() => {
        console.log(2)
    });
    func1();
    console.log(3);
    p.then(resolved => {
        console.log(resolved)
    }).then(() => {
        console.log(6)
    });
}
func2();
 Copy code 

answer :4 1 3 5 6 2

I don't know if you're right ?

If the answer is right , You are right. JS Have a deep understanding of the implementation mechanism , Continue to look down to review and consolidate ; If you don't know or answer wrong , Don't be sad , The following part of this article will give you the answer

We know js One of the main features of is single thread , Only one thing can be done at a time . But why should it be designed as a single thread ? In fact, it has something to do with its purpose ,js Script language as browser , The main purpose is for user interaction and operation DOM. Think about if it's designed to be multithreaded , A thread in a DOM Add content on node , Another thread is deleting this node , Who should the browser listen to ?

therefore , In order to avoid the complex problems caused by multithreading , Decided from the beginning of the design JS It's a single thread , This is called the core feature of the language , It won't change in the future .

To take advantage of multiple cores CUP Computing power ,HTML5 Put forward Web Worker standard , allow JS Create multiple threads , But the child thread is completely under the control of the main thread , And the child thread cannot operate DOM. therefore , The new standard has not changed js The nature of single threads .

Single thread means , All tasks are queued , The previous task is over , Will perform the latter task . If the previous task took a long time , The latter task had to wait . But if some tasks are slow ( such as Ajax Operations to read data from the network ), Do I still have to wait for the results to perform the next task ? This is not good

therefore , There is an asynchronous task .

Synchronous task refers to , Tasks queued for execution on the main thread , Only the previous task was completed , To perform the next task ; Asynchronous tasks refer to , Do not enter the main thread 、 And enter " Task queue "(task queue) The task of , Only the main thread has finished executing , The main thread notifies " Task queue ", Some asynchronous task is ready to execute , This task is then executed on the main thread .

So actually js Multithreading is implemented asynchronously

The operation mechanism is as follows :

(1) All synchronization tasks are performed on the main thread , Form an execution stack (Call Stack)

(2) Outside the main thread , There is also a " Task queue "(task queue). As long as asynchronous tasks have run results , It's just " Task queue " Put an event

(3) once " Execution stack " All synchronization tasks in are completed , The system will read " Task queue ", See what's going on inside . Those corresponding asynchronous tasks , So the waiting state is ended , Enter the execution stack , Start execution .

(4) The main thread repeats step 3 above .

The execution stack is used to organize JS Code , guarantee JS Orderly execution of code . Whenever a function is called , Will push the function into the execution stack , Pop up after execution , Then call the next function

In the second step , In fact, the running results of asynchronous tasks are backed by other threads of the browser

Browser kernel resident thread :

  1. js Engine threads

Used to interpret execution js Code 、 User input 、 Network request, etc

  1. GUI Rendering thread

Drawing the user interface , And JS Main threads are mutually exclusive ( because js Can operate DOM, In turn, it will affect GUI The rendering result of )

  1. http Asynchronous network request thread

Handle user's get、post Equal request , After returning the result, push the callback function to the task queue

  1. Timing trigger thread

setInterval、setTimeout When the waiting time is over , Will push the execution function into the task queue

  1. Browser event handling thread

take click、mouse After the interaction event , Put the callback function to be executed into the event queue

Task queue " It's a first in, first out data structure , The events at the front , Priority read by main thread .

The main route is empty , Will read again " Task queue ", However, task queues vary in different hosting environments , Most hosting environments divide task queues into macrotask( Macro task ) and microtask( Micro task )

Macro tasks mainly include :script( The overall code )、setTimeout、setInterval、I/O、UI Interactive events 、setImmediate(Node.js Environmental Science )

Micro tasks mainly include :Promise then、async await、MutaionObserver、process.nextTick(Node.js Environmental Science )

When performing stack emptying ,JS The engine will first finish executing all the tasks in the micro task in turn , If there are no micro tasks , Then execute the macro task .

" The reading process of the main thread is basically automatic , As soon as the stack is emptied ," Task queue " The first event on the thread automatically enters the main thread . But the timer first checks whether the execution time is up , At the appointed time , Before entering the main thread to execute , After execution, read the next event in the task queue , This process is a continuous cycle , We call the mechanism of this cycle Event Loop( The event loop ), namely

When the main thread is running , Make a pile (heap) And the stack (stack), The code in the stack calls all kinds of external API( That is, various functions ), They are " Task queue " Add all kinds of events (click,load,done). As long as the code in the stack is executed , The main thread will read " Task queue ", Execute the callback function corresponding to those events in turn .

Let's look at the timer

If you will setTimeout() The second parameter of is set to 0, Indicates that after stack emptying , Execute now (0 Millisecond interval ) The specified callback function .

setTimeout(function(){console.log(1);}, 0);
console.log(2);
 Copy code 

The result is 2,1, Because only after executing the second line , The system will execute " Task queue " The callback function in .

HTML5 The standard stipulates setTimeout() The minimum value of the second parameter of ( Minimum interval ), Not less than 4 millisecond , If it's below this value , It will automatically increase . Before that , Old browsers set the minimum interval to 10 millisecond . in addition , For those who DOM The change of ( Especially when it comes to re rendering pages ), Usually not immediately , But every 16 Execute in milliseconds .

It should be noted that ,setTimeout() Just insert the event into " Task queue ", You have to wait until the current code ( Execute the stack and the top micro tasks ) After execution , The main thread will execute the callback function specified in the timer . If the current code takes a long time , It could take a long time , So there's no way to guarantee , The callback function must be in setTimeout() At a specified time .

Finally, come back and look at the topic above :

// What is the execution result of the following code 
var p = new Promise(resolve => {
    console.log(4);
    resolve(5);
});
function func1() {
    console.log(1)
}
function func2() {
    setTimeout(() => {
        console.log(2)
    });
    func1();
    console.log(3);
    p.then(resolved => {
        console.log(resolved)
    }).then(() => {
        console.log(6)
    });
}
func2();
 Copy code 

perform

First step :new Promis Press into the execution stack , Then execute the code inside , Print 4, perform resolve(5); Pay attention to the following new Like ordinary functions, they execute normally , Will not be added to the macro task ;

The second step : perform func2(), encounter setTimeout, Put it in the macro task ;

Then perform func1(); Print out 1

next console.log(3); Print 3

encounter Promise Object to perform then() when , Here is asynchronous operation , The callback function will be put into the micro task , Waiting for execution When the execution stack is emptied , Execute... In micro tasks console.log(resolved), Print out 5, Then go to the micro task to find the next event , Print out 6;

When the micro task is empty , Then execute the macro task , namely setTimeout I'll promise when the time comes 2,

So the final answer is :4 1 3 5 6 2

That's the timer and JS Relevant contents of the implementation mechanism

copyright notice
author[LBJ],Please bring the original link to reprint, thank you.
https://en.qdmana.com/2021/08/20210827045918822F.html

Random recommended