js执行机制
https://juejin.im/post/6844903512845860872
https://juejin.im/post/6844903764202094606 如有帮助,请感谢掘金作者!!
- 同步和异步任务分别进入不同的执行场所,同步的进入主线程,异步的进入Event Table并注册函数。
- 当指定的事情完成时,Event Table会将这个函数移入Event Queue。
- 主线程内的任务执行完毕为空,会去Event Queue读取对应的函数,进入主线程执行。
- 上述过程会不断重复,也就是常说的Event Loop(事件循环)。
那怎么知道主线程执行栈为空?js引擎存在monitoring process进程,会持续不断的检查主线程执行栈是否为空,一旦为空,就会去Event Queue那里检查是否有等待被调用的函数。
异步任务有两种类型:宏任务(macrotask)和微任务(microtask)。
macro-task(宏任务)
- setTimeout
- setInterval
- setImmediate
- MessageChannel
- requestAnimationFrame
- I/O
- UI交互事件
micro-task(微任务)
- Promise
- MutationObserver
- Object.observe
- process.nextTick
js执行机制关键理解 *把下面的解释理解清楚,再知道什么是宏任务、什么是微任务,js执行机制就彻底明白了*
js执行机制关键理解事件循环的顺序,决定js代码的执行顺序。
进入整体代码(宏任务)后,开始第一次循环。
接着执行所有的微任务。
然后再次从宏任务开始,找到其中一个任务队列执行完毕,再执行所有的微任务。
async function fn(){
await f
console.log('ok')
}
// 简化理解为:
function fn(){
return Promise.resolve(f).then(()=>{
console.log('ok')
})
}
执行机制输出结果
console.log(0)
setTimeout(function(){
console.log(1)
setTimeout(function(){
console.log(2)
new Promise((resolve) => {
console.log(3)
resolve()
}).then(() => {
console.log(4)
})
}, 0)
}, 0)
new Promise((resolve) => {
console.log(5)
resolve()
}).then(() => {
new Promise((resolve) => {
console.log(6)
setTimeout(function() {
resolve()
}, 0)
}).then(() => {
console.log(7)
setTimeout(function() {
console.log(8)
}, 0)
})
})
$.ajax({
url: '',
success: function() {
console.log(9)
}
})
console.log(10)
输出结果:0, 5, 10, 6, 1, 7, 2, 3, 4, 8, 9
以自己现在的努力程度,还没有资格和别人拼天赋

浙公网安备 33010602011771号