First, JavaScript running steps
// 基本概念1、代码块:一个<script>就是一个代码块。代码块间相互独立,但变量和方法共享。2、声明式函数与赋值式函数:声明式函数:会提升方法体赋值式函数:如同普通变量,到达赋值时,才有方法体3、预编译期与执行期:变量及函数声明的提升// 运行步骤1. 读入第一个代码块。2. 做语法分析,有错则报语法错误(比如括号不匹配等),并跳转到step5。3. 对var变量和function定义做“预编译处理”(永远不会报错的,因为只解析正确的声明)。4. 执行代码段,有错则报错(比如变量未定义)。5. 如果还有下一个代码段,则读入下一个代码段,重复step2。6. 结束。
Second, javascript operating mechanism
JS engine will generate two queues: Macrotask queue
andMicrotask Queue
Creation of Task
macrotasks
:
script, setTimeout, setInterval, setImmediate, I/O, UI rendering
microtasks
:
process.nextTick, Promise, Object.observe, MutationObserver
JavaScript engine operating mechanism:
- The default is to start execution from the first task in the Macrotask queue (because script is macrotask), and when a macro or micro task is encountered, it is added to the corresponding queue;
- Remove all Microtask queue tasks and execute all microtask sequentially;
- Remove the next macro queue again and execute (same as step 1);
- Repeat 2,3
- End of execution
Description: An error in a task that affects only subsequent code in the current task tasks
Such as:
setTimeout(() => { console.log(‘task1‘); // aaa 不存在,报错 console.log(aaa); // 这行不执行,因为被阻断 console.log(22222);}, 1000);// 上一个错误不影响此任务执行setTimeout(() => console.log(‘task2‘), 3000);
Results:
Three, complete example:
console.log(‘000‘);Promise.resolve().then(() => { console.log(111); Promise.resolve().then(() => console.log(222)); setTimeout(() => console.log(333));}).then(() => { console.log(444);});setTimeout(() => { console.log(555); Promise.resolve().then(() => console.log(666));});Promise.resolve().then(() => { console.log(777); Promise.resolve().then(() => console.log(888));});setTimeout(() => console.log(999));console.log(‘aaa‘);
Results:
000aaa111777222444888555666999333
Diagram Analysis:
- ① executes the main macrotask and generates a new queue.
- ② the new queue.
- ③ executes all microtask and adds the new task to the corresponding queue until all the tasks in the Microtask queue are executed.
- ④ executes a macrotask and immediately executes the Microtask Queue.
- ⑤ repeat the above steps until the end.
JavaScript operating mechanism