Created
November 6, 2018 00:05
-
-
Save shaoshing/bc88b16e53d2688e59594b8011607652 to your computer and use it in GitHub Desktop.
Nodejs event loop: setTimeout v.s. setImmediate v.s. process.nextTick
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const fs = require("fs"); | |
// The execution order of the setTimeout and setImmedate callbacks are non-deterministic. | |
setTimeout(() => { | |
console.info("setTimeout in main"); | |
}, 0); | |
setImmediate(() => { | |
console.info("setImmediate in main"); | |
}); | |
fs.readFile(__filename, () => { | |
// When the Event Loop is in the I/O phase, setImmediate callbacks will always executed before setTimeout callbacks | |
// since the next phase will be "check" phase where the setImmediate callbacks are queued. | |
console.info("readFile"); | |
setTimeout(() => { | |
console.info("setTimeout in I/O"); | |
}, 0); | |
setImmediate(() => { | |
console.info("setImmediate in I/O"); | |
}); | |
// nextTick callbacks are always processed immediately after the current operation is completed | |
process.nextTick(() => { | |
console.info("nextTick"); | |
}); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment