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 running code after a delay, repeating actions periodically, or running code after completing certain operations.

Some of them are no different from those found on a web page. But others are specific to the Node.js environment.

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 execute a function repeatedly at a specified interval, also expressed in milliseconds.

const interval = 2000; // 2 seconds

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

// To stop the interval after a certain 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('It has 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 cycle of events.

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

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.');
});