Skip to content

Instantly share code, notes, and snippets.

@shaoshing
Created November 6, 2018 00:05
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save shaoshing/bc88b16e53d2688e59594b8011607652 to your computer and use it in GitHub Desktop.
Save shaoshing/bc88b16e53d2688e59594b8011607652 to your computer and use it in GitHub Desktop.
Nodejs event loop: setTimeout v.s. setImmediate v.s. process.nextTick
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