Skip to content

Instantly share code, notes, and snippets.

@benjamingr
Created April 24, 2017 16:43
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save benjamingr/9afb9c52facd31484d5fc2e382de44c7 to your computer and use it in GitHub Desktop.
Save benjamingr/9afb9c52facd31484d5fc2e382de44c7 to your computer and use it in GitHub Desktop.
// what's the output?
setTimeout(() => {
console.log('timer1');
process.nextTick(() => console.log('timer1 nextTick'));
Promise.resolve().then(() => console.log('timer1 resolve'));
});
setTimeout(() => console.log('timer2'));

The output is

timer1
timer2
timer1 nextTick
timer1 resolve
  • All synchronous code is run (setting the timers).
  • The event loop waits (poll) for the timers to fire, then their callbacks are all called.
  • Then anything in the nextTick queue is run
  • Then any resolved promises run their then handlers
  • If anything is in the nextTick or promises queue at this point (because other handlers added it) jump two steps up.
  • The event loop waits (poll) for the timers to fire, then their callbacks are all called...
@wis
Copy link

wis commented Mar 31, 2021

Hey @benjamingr
why is the output for me (Node v15.12.0) different:

timer1
timer1 nextTick
timer1 resolve
timer2

how did the behavior of Node/V8 change since?

@benjamingr
Copy link
Author

I don't remember this gist or its context but your output aligns with my understanding - microticks are always run between timers.

In general between every two macro-tasks that happen (like I/O or timers) microtasks (like process.nextTick or promise callbacks) need to run to completion - it's possible I created this gist in order to point out a bug in case this was not the case.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment