当前位置:网站首页>Overview of JS synchronous, asynchronous, macro task and micro task
Overview of JS synchronous, asynchronous, macro task and micro task
2022-07-25 15:12:00 【Deep sea blue mountains】
One 、 Event cycle mechanism

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, 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 .
When the main thread runs, it will produce an execution stack , The code in the stack calls some api when , They add various events to the event queue
And the code in the stack is executed , It will read the events in the event queue , To execute those callbacks
So circular
Be careful , Always wait for the code in the stack to execute before reading the events in the event queue
Two 、 Synchronization task 、 Asynchronous task
JS It's single threaded , Single thread means , All tasks are queued , The previous task is over , Will perform the latter task . In order to solve the problem of waiting ,JS Tasks of are divided into synchronization tasks (synchronous) And asynchronous tasks (asynchronous).
All synchronization tasks are performed on the main thread , Form an execution stack . Asynchronous tasks do not enter the main thread , But into another 【 Task queue 】. Synchronous tasks are executed sequentially , Only the synchronization task in the execution stack is completed , The system will read back the asynchronous tasks that can be executed in the task queue , Will put this asynchronous task from the event queue into the execution stack for execution , So circular , Until all tasks are completed .

- Synchronous code is executed directly
- The asynchronous function is put into the asynchronous queue at the specified time
- Synchronization complete , Asynchronous queue polling execution .
3、 ... and 、 Macro task 、 Micro task
macrotask( Macro task ), It can be understood that the code executed by each stack is a macro task ( It includes getting an event callback from the event queue and putting it into the execution stack to execute )
every last task Will finish the task from beginning to end , No other
Browser in order to be able to make JS Inside task And DOM Tasks can be executed orderly , In a task After execution , The next task Before execution , Re render the page
Micro tasks can be created in macro tasks , However, the micro task created in the macro task will not affect the execution of the current macro task
When all the tasks in a macro task queue are executed , It checks to see if there is a queue of microtasks , If so, all tasks in the micro task queue will be executed first , If not, check whether there is a macro task queue
Common macro tasks :I/O,setTimeout,setInterval

microtask( Micro task ), It can be understood that in the present task Tasks to be performed immediately after the completion of execution
in other words , At present task After the task , next task Before , Before rendering
So it's faster than setTimeout(setTimeout yes task) Will be faster , Because there's no need to wait for rendering
After the execution of the previous macro task queue , If there is a micro task queue, all tasks in the micro task queue will be executed
new promise((resolve)=>{ The functions here are executed directly in the current queue }).then( The functions here are executed in the micro task queue )
Micro tasks created on the micro task queue , It will still block the macro task queue to be executed later
Macro tasks created by micro tasks , Will be left in the asynchronous macro task queue for execution
Common micro tasks :Promise,process.nextTick
summary :
- Micro task queue takes precedence over macro task queue ,
- The macro task created on the micro task queue will be added to the end of the current macro task queue , The micro task created in the micro task queue will be added to the end of the micro task queue .
- As long as there are tasks in the micro task queue , The macro task queue will only wait for the micro task queue to execute after execution
3、 ... and 、 Execution order
1. Macro task on main thread 、 Micro task execution sequence
console.log('---start---');// The first round of main thread
setTimeout(() => {
console.log('setTimeout'); // Put the callback code into a macro task queue , The second round of macro task execution
}, 0);
new Promise((resolve, reject) => {
console.log('---Promise The first round of micro tasks is executed synchronously ---');// The first round of micro tasks is executed synchronously
resolve()
}).then(()=>{
console.log('Promise.then The instance successfully called back to execute '); // Put the callback code into the micro task queue , Execute immediately after the first round of macro tasks
});
console.log('---end---');// The first round of main thread ends
Execution order : The main thread >> Micro tasks created on the main thread >> Macro tasks created on the main thread

2. Macro tasks include micro tasks
// Macro task queue 1
setTimeout(() => {
// Macro task queue 2.1
console.log('timer_1');
setTimeout(() => {
// Macro task queue 3
console.log('timer_3')
}, 0)
new Promise(resolve => {
resolve()
console.log('new promise')
}).then(() => {
// Micro task queue 1
console.log('promise then')
})
}, 0)
setTimeout(() => {
// Macro task queue 2.2
console.log('timer_2')
}, 0)
console.log('========== Sync queue ==========')Execution order : The main thread >> Macro task queue on main thread 1 >> Macro task queue 1 Micro tasks created in
========== Sync queue ==========
1 timer_1
2 new promise
3 promise then
4 timer_2
5 timer_3
边栏推荐
- pkg_ Resources dynamic loading plug-in
- Add the jar package under lib directory to the project in idea
- Idea远程提交spark任务到yarn集群
- golang复习总结
- ES5写继承的思路
- 记一次Spark报错:Failed to allocate a page (67108864 bytes), try again.
- Cmake specify opencv version
- [Nacos] what does nacosclient do during service registration
- 记一次redis超时
- Content type corresponding to office file
猜你喜欢

Leo-sam: tightly coupled laser inertial odometer with smoothing and mapping

43 box model

Process control (Part 1)

图片裁剪cropper 示例

VMware Workstation fails to start VMware authorization service when opening virtual machine

How much memory can a program use at most?

用setTimeout模拟setInterval定时器

记一次Spark foreachPartition导致OOM

ice 100G 网卡分片报文 hash 问题

Debounce and throttle
随机推荐
Sublimetext-win10 cursor following problem
记一次Spark foreachPartition导致OOM
Debounce and throttle
When using jetty to run items, an error is reported: form too large or form too many keys
Splice a field of the list set into a single string
记一次Spark报错:Failed to allocate a page (67108864 bytes), try again.
TypeScript学习2——接口
Use the command to check the WiFi connection password under win10 system
Handle Oracle deadlock
6线SPI传输模式探索
任务、微任务、队列和调度(动画展示每一步调用)
继承的实现过程及ES5和ES6实现的区别
解决DBeaver SQL Client 连接phoenix查询超时
TypeScript学习1——数据类型
Leetcode combination sum + pruning
pkg_ Resources dynamic loading plug-in
dpdk 收发包问题案例:使用不匹配的收发包函数触发的不收包问题定位
ESXI6.7.0 升级到7.0U3f(2022年7月12 更新)
Cmake specify opencv version
Nacos2.1.0 cluster construction