Skip to content

Instantly share code, notes, and snippets.

@danmactough
Created December 31, 2013 00:22
Show Gist options
  • Save danmactough/8190476 to your computer and use it in GitHub Desktop.
Save danmactough/8190476 to your computer and use it in GitHub Desktop.
Isaac's description of process.nextTick vs. setImmediate

I agree the point you’re making here, 100%. However, a slight correction about Node’s APIs.

First of all, process.nextTick is actually first in, first out. Proof:

$ node -e 'process.nextTick(console.log.bind(console, 1)); process.nextTick(console.log.bind(console, 2))'
1
2

Second, process.nextTick isn’t quite the same as setImmediate, at least as of 0.10. Node has a setImmediate function which does happen on the next turn of the event loop, and no sooner. process.nextTick happens before the next turn of the event loop, so it is not suitable for deferring for I/O. It IS suitable for deferring a callback until after the current stack unwinds, but making sure to call the function before any additional I/O happens. In other words, every entrance to JS from the event loop goes like:

  • Event loop wakes up (epoll, etc.)
  • Do the thing that you said to do when that event happens (call handle.onread or whatever)
  • Process the nextTick queue completely
  • Return to the loop

setImmediate is something like a timer that schedules an immediate wake-up, but on the next turn of the event loop. (It’s been pointed out that they’re named incorrectly, since setImmediate is on the next “tick”, and process.nextTick is “immediate”, but whatever, naming stuff is hard, and we’re borrowing the bad name from the browser spec.)

The difference may seem like a minor nit-pick, but it’s actually quite relevant. If you are recursively calling process.nextTick, then you’re never actually yielding to the event loop, so you’re not accepting new connections, reading files and sockets, sending outgoing data, etc.

But that aside, yes. It is completely baffling to me that there is any resistance to this API in browsers, where it is so clearly an obvious win.

Isaac Schlueter on July 9th, 2013 at 1:01 pm http://www.nczonline.net/blog/2013/07/09/the-case-for-setimmediate/ (in the comments)

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