blog icon indicating copy to clipboard operation
blog copied to clipboard

macrotasks vs microtasks

Open luckyyyyy opened this issue 6 years ago • 0 comments

macrotasks

func Browser Node
I/O
setTimeout
setInterval
setImmediate
requestAnimationFrame

microtasks

func Browser Node
Iprocess.nextTick
MutationObserver
Promise.then catch finally
// see: https://gist.github.com/yyx990803/d1a0eaac052654f93a1ccaab072076dd

// macrotasks: setTimeout, setInterval, setImmediate, I/O, UI rendering
// microtasks: process.nextTick, Promise, MutationObserver

console.log(1)

setTimeout(() => {
    console.log(2)
}, 0);

setTimeout(() => {
    console.log(3)
}, 0);

new Promise((resolve, reject) => {
    console.log('Promise 1');
    resolve();
}).then(() => {
    console.log('Promise 2');
}).then(() => {
    console.log('Promise 3');
});

process.nextTick(() => {
    console.log('process 1')
});

process.nextTick(() => {
    console.log('process 2')
});
/**
 * ➜  ~ node task.js
 * 1
 * Promise 1
 * process 1
 * process 2
 * Promise 2
 * Promise 3
 * 2
 * 3
 */

luckyyyyy avatar Feb 25 '19 03:02 luckyyyyy