怎麼理解 microtask & macrotask

雖然是面試常見題,但不要背誦答案,深入探索這個問題的本質,過程其實還蠻有趣的。

Definition

macrotask = task

那什麼是 microtask ?

Pseudo Code — event loop

Comparison case

setTimeout(()=> console.log('timer'),0) 
// -> enqueue in task queue
Promise.resolve().then(()=>console.log('promise'))
// -> enqueue in microtask queue
// output:
// promise (below the task queue done)
// timer (next while iteration)
/** 
our busy waiting logic...
while(true) {
task = eventLoop.nextTask();
if (task) {
task.execute(); // now we execute above two line
}
eventLoop.executeMicrotasks();
// promise callback, print promise (1)
if (eventLoop.needsRendering())
eventLoop.render();
}

// timer (2) (next while iteration)
**/

Order inconsistent case

const cache = {};
const myFetch = url => {
if (cache[url]) {
console.log(cache[url])
} else {
fetch(url).then(result => result.arrayBuffer()).then(data => {
cache[url] = data;
console.log(data)
});
}
};
console.log('start');
myFetch('/test123')
console.log('done')
start
cache result
done
start
done
fetch result
const cache = {};
const myFetch = url => {
if (cache[url]) {
Promise.resolve().then(()=>console.log(cache[url]))
} else {
fetch(url).then(result => result.arrayBuffer()).then(data => {
cache[url] = data;
console.log(data)
});
}
};
start
done
result

還有哪些是 microtask ?

RequestAnimationFrame 的 callback 跟這兩者的順序?

1. Do the oldest (macro) task
2. Do microtasks
3. If this is a good time to render:
- Do some prep work
- Run requestAnimationFrame callbacks
- Render

尾聲

補充

If any interest, 👉 https://realdennis.me.

If any interest, 👉 https://realdennis.me.