当前位置:网站首页>Operating principle of JS core EventLoop

Operating principle of JS core EventLoop

2022-06-13 02:46:00 Zeng Qiang

Catalog

background

Javascript The runtime environment for

Synchronous and asynchronous

EventLoop Operating mechanism

case analysis

extend : Macro task and micro task

summary

Reference link



background

Javascript The runtime environment for

Javascript The runtime environment of is generally referred to as the browser or Node.js. Generally speaking Javascript The runtime environment is used in addition to parsing and executing JS Code Javascript engine , It also includes WebAPI, Thread pool , Task queue ,EventLoop wait . When these components are combined, they are Javascript Provide an asynchronous and responsive environment .

Synchronous and asynchronous

Sync : You can only do one thing at a time .Javacript The engine is a single thread . Responsible for interpreting and executing JavaScript Code this means you can only do one thing at a time . It's like a one-way street , Only one car at a time , It is easy to cause blockage .

A single thread can only do synchronous operations , So how to solve the problem caused by blocking ? Asynchronous programming .Javascript The runtime provides a EventLoop Event cycle model for , To handle asynchronous operations . Now I will start from EventLoop Structure and code case of , Two aspects of analysis EventLoop working principle .

EventLoop Operating mechanism

overview :EventLoop stay Javascript Runtime ( Browser environment ) The location of .

Call stack: Call Stack .JS Execute one line of code at a time ,

WebAPI: When the call stack encounters setTimeout(callback,timeout)API When , The timer that will be given to the browser counts down , After time , Will be able to callback Push the callBackQueue in .

CallbackQueue:callBackQueue Used to save callback functions

EventLoop: The event circulator periodically detects whether the call stack is empty , If the call stack is empty , It will put callbackQueue Callback out of the queue , Put it into the call stack to execute .

RenderQueue: Render event queue .EventLoop Priority will be given to the... In the rendering queue callback.

  The code that calls the stack is in JS Executed in a single thread . therefore callback And call stack if the execution time is too long , It will cause the process of page rendering to be blocked .

GUI In process GUI The rendering thread is responsible for page rendering , But the same thing JS Is mutually exclusive , Both pass EventLoop signal communication .

case analysis

function pipe(){
 console.log('do easy sth... 1');
 setTimeout(function (){
        console.log("do hard sth... 2")
    }, 1000)
 setTimeout(function (){
        console.log("do hard sth... 3")
    }, 1000)
 setTimeout(function (){
        console.log("do hard sth... 4")
    }, 1000)
 setTimeout(function (){
        console.log("do hard sth... 5")
    }, 1000)
 setTimeout(function (){
        console.log("do hard sth... 6")
    }, 1000)
   
    console.log('do easy sth... 7')
}
// Output :1,7,2,3,4,5,6

Why the above code output is not 1,2,3,4,5,6,7? This is because ,JS Execute the code in the call stack first , therefore 1 ,7 Will print first , secondly setTimeout Will put it callback Put it in Callback The queue is waiting to be EventLoop Dispatch . and EventLoop Only when the call stack is empty , Will be scheduled in turn CallBack queue . So we should try our best to ensure UI Rendering is performed forward , And the call stack should not do time-consuming operations .

extend : Macro task and micro task

Micro task :Promise Every time you call then() when , Registered tasks .

Macro task :callback Every frame in the queue or call stack is a macro task , The current micro task queue will be executed immediately after the macro task is executed , Then you can switch to the rendering thread to perform the page rendering task .

The relationship between them :  Macro task -> Micro task -> Rendering tasks --> Macro task ...

summary

EventLoop yes GUI The common asynchronous programming model in programming ,Android It is also in development . The call stack is like a pipeline , Specializing in the production of products , Encounter tasks that require time-consuming operations , Just throw it to the product polishing Department (WebAPI), The product polishing department finishes the time-consuming task , The result of the mission , Put in a queue , hand EventLoop This dispatcher dispatches ,EventLoop When the monitoring assembly line is free, it will rotate training callback queue , hold CallBack The time-consuming task results of the queue are displayed , Let the assembly line continue to work .

Reference link

From browser multiprocessing to JS Single thread ,JS The most comprehensive carding of operation mechanism - Nuggets Opinions are limited , If there is any improper description , Please point out in time , If there is a mistake , Will fix in time . ---------- Super long text + Multi map early warning , It takes a lot of time .---------- If after reading this article , Also confused about the process thread , Not clear about browser multiprocess 、 Browser kernel multithreading 、JS Single thread 、JS The difference in operating mechanism . Then please reply me , It must be me …https://juejin.cn/post/6844903553795014663#heading-21

【 Homemade cooked meat 】Philip Roberts: What exactly is Event Loop Well ?(JSConf EU 2014)_ Bili, Bili _bilibili Take time to translate the speech video , Great talk , You can have a look https://www.bilibili.com/video/BV1oV411k7XY/

原网站

版权声明
本文为[Zeng Qiang]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/02/202202280538227100.html