Skip to content

Instantly share code, notes, and snippets.

@psenger
Created April 25, 2023 09:19
Show Gist options
  • Save psenger/4437339e1a326e9966e2b6c6cdd6ecd6 to your computer and use it in GitHub Desktop.
Save psenger/4437339e1a326e9966e2b6c6cdd6ecd6 to your computer and use it in GitHub Desktop.
[process.nextTick setImmediate] #NodeJS

Process NextTick and SetImmediate

In Node.js, process.nextTick() is a method that allows you to schedule a function to be executed on the next iteration of the event loop. It is often used to defer the execution of a function until after the current function has completed.

The process.nextTick() method is similar to setImmediate(), but with a few key differences. While setImmediate() schedules a callback to run in the next iteration of the event loop, process.nextTick() schedules a callback to run at the end of the current iteration of the event loop, before any I/O operations.

Here is an example of how process.nextTick() can be used:

console.log('start');

process.nextTick(() => {
  console.log('nextTick callback');
});

console.log('end');

In this example, the output would be:

start
end
nextTick callback

This is because the console.log('nextTick callback') statement is deferred until after the current function has completed, and is therefore executed after the console.log('end') statement.

It's worth noting that process.nextTick() can be used to create an infinite loop if not used correctly, so it's important to be careful when using it.

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