Language: EN

funciones-temporales-nodejs

Temporary Functions and Timers in Node.js

In Node.js, temporary functions and timers allow us to execute functions asynchronously after a certain time or at regular intervals.

These timers are essential for tasks such as executing code after a delay, repeating actions periodically, or executing code after completing certain operations.

Some of them are not different from those we find on a web page. But others are specific to the Node.js realm.

Examples of temporary functions

setTimeout

The setTimeout method is used to execute a function after a specified period of time, expressed in milliseconds.

const delay = 3000; // 3 seconds

const timeoutId = setTimeout(() => {
  console.log('3 seconds have passed!');
}, delay);

// To cancel the timeout before it executes
// clearTimeout(timeoutId);

In this example, the function passed as an argument will be executed after 3 seconds.

setInterval

The setInterval method is used to repeatedly execute a function every specified interval of time, also expressed in milliseconds.

const interval = 2000; // 2 seconds

const intervalId = setInterval(() => {
  console.log('Hello every 2 seconds!');
}, interval);

// To stop the interval after some time
/* setTimeout(() => {
  clearInterval(intervalId);
}, 10000); */ // Stop after 10 seconds

In this example, the function passed as an argument will be executed every 2 seconds.

Combined example of setTimeout and clearInterval

In this example, we use setInterval to execute a function every second and stop it after 5 seconds:

let seconds = 0;

const intervalId = setInterval(() => {
  seconds++;
  console.log('There have been ' + seconds + ' seconds.');

  if (seconds === 5) {
    clearInterval(intervalId);
    console.log('The interval stopped after 5 seconds.');
  }
}, 1000); // Every second

setImmediate

The setImmediate method is used to execute a function in the next event cycle.

setImmediate(() => {
  console.log('This executes in the next event cycle.');
});

process.nextTick

The process.nextTick method is used to execute a function at the end of the current JavaScript execution cycle, but before any I/O or timers. For example:

process.nextTick(() => {
  console.log('This executes at the end of the current cycle.');
});

Download the code

All the code from this entry is available for download on Github github-full