61

I have seen process.nextTick used in a few places and can't quite tell what it's being used for.

What are the main/proper use cases of process.nextTick in Node.js? The docs basically say it's a more optimized way of doing setTimeout, but that doesn't help much.

I used to do a lot of ActionScript, so the idea of "waiting until the next frame" to execute code makes sense on some level - if you're running an animation you can have it update every frame rather than every millisecond for example. It also makes sense when you want to coordinate setting a bunch of variables - you change the variables in frame 1, and apply the changes in frame 2. Flex implemented something like this in their component lifecycle.

My question is, what should I be using this for in server-side JavaScript? I don't see any places right off the bat where you'd need this kind of fine-tuned performance/flow control. Just looking for a point in the right direction.

Lance
  • 75,200
  • 93
  • 289
  • 503
  • 2
    Howtonode has an [excellent article on understanding `process.nextTick()`](http://howtonode.org/understanding-process-next-tick) – Dan Dascalescu May 12 '13 at 06:16

3 Answers3

72

process.nextTick puts a callback into a queue. Every callback in this queue will get executed at the very beginning of the next tick of the event loop. It's basically used as a way to clear your call stack. When the documentation says it's like setTimeout, it means to say it's like using setTimeout(function() { ... }, 1) in the browser. It has the same use cases.

One example use case would be, you create a constructor for some object that needs events bound to it. However, you can't start emitting events right away, because the code instantiating it hasn't had time to bind to events yet. Your constructor call is above them in the call stack, and if you continue to do synchronous things, it will stay that way. In this case, you could use a process.nextTick before proceeding to whatever you were about to do. It guarantees that the person using your constructor will have time enough to bind events.

Example:

var MyConstructor = function() {
  ...
  process.nextTick(function() {
    self._continue();
  });
};

MyConstructor.prototype.__proto__ = EventEmitter.prototype;

MyConstructor.prototype._continue = function() {
  // without the process.nextTick
  // these events would be emitted immediately
  // with no listeners. they would be lost.
  this.emit('data', 'hello');
  this.emit('data', 'world');
  this.emit('end');
};

Example Middleware using this constructor

function(req, res, next) {
  var c = new MyConstructor(...);
  c.on('data', function(data) {
    console.log(data);
  });
  c.on('end', next);
}
Dan Dascalescu
  • 143,271
  • 52
  • 317
  • 404
chjj
  • 14,322
  • 3
  • 32
  • 24
  • 3
    Also, setTimeout is too slow. – Parris Feb 17 '13 at 01:51
  • 7
    "Every callback in this queue will get executed at the very beginning of the next tick of the event loop." I think this isn't entirely accurate anymore. As I understand it, the queue is processed at the end of the current tick. "In v0.10, nextTick handlers are run right after each call from C++ into JavaScript. That means that, if your JavaScript code calls process.nextTick, then the callback will fire as soon as the code runs to completion, but before going back to the event loop." - from [Node 0.10.0 announcement](http://blog.nodejs.org/2013/03/11/node-v0-10-0-stable/) – Myrne Stol May 12 '13 at 11:47
17

It simply runs your function at the end of the current operation before the next I/O callbacks. Per documentation you can use it run your code after the callers synchronous code has executed, potentially if you can use this to give your API/library user an opportunity to register event handlers which need to be emitted ASAP. Another use case is to ensure that you always call the callbacks with asynchronously to have consistent behaviours in different cases.

In the past process.nextTick would be have been used provide an opportunities for I/O events to be executed however this is not the behaviour anymore and setImmediate was instead created for that behaviour. I explained a use case in the answer of this question.

Farid Nouri Neshat
  • 29,438
  • 6
  • 74
  • 115
  • "It simply puts your function at the end of the event loop." - no it doesn't, nextTick is executed at the end of the current operation, BEFORE the event loop continues. – Marko Aug 29 '21 at 02:02
  • @Marko Thanks, sorry this was the old behaviour, which I didn't bother to update it. It is updated now, thanks for the notice. – Farid Nouri Neshat Aug 29 '21 at 13:52
0

"Every callback in this queue will get executed at the very beginning of the next tick of the event loop" is not correct. Actually, nextTick() runs right after completing the current phase and before starting the next phase. Minute details are important!

A function passed to process.nextTick() is going to be executed on the current iteration of the event loop, after the current operation ends. This means it will always execute before setTimeout and setImmediate.

Understanding setImmediate()