nodejs
  1. nodejs-timer-functions

Node.js Timer Functions

Node.js provides timer functions that allow you to execute a piece of code at a set interval or after a specified amount of time has passed. In this tutorial, we'll take a look at the timer functions in Node.js and how to use them to schedule code execution.

Syntax

There are three timer functions available in Node.js:

1. setTimeout()

The setTimeout() function executes a piece of code once after a specified delay.

setTimeout(callback, delay);

2. setInterval()

The setInterval() function executes a piece of code repeatedly at a set interval until the timer is cleared.

setInterval(callback, delay);

3. setImmediate()

The setImmediate() function executes a piece of code immediately after the current event loop iteration is completed.

setImmediate(callback);

Example

Let's take a look at an example of how to use the setTimeout() function in Node.js. In this example, we'll execute a piece of code after a delay of 3 seconds:

function printHello() {
  console.log("Hello, world!");
}

setTimeout(printHello, 3000);

After 3 seconds, the "Hello, world!" message will be printed to the console.

Output

When we run the example code above, the output will be:

Hello, world!

This is because the setTimeout() function executed the printHello() function after a delay of 3 seconds, which printed the message to the console.

Explanation

In the example above, we used the setTimeout() function to execute a piece of code after a delay of 3 seconds. We defined a function called printHello() that simply prints the message "Hello, world!" to the console. We then passed this function as a callback to the setTimeout() function along with a delay of 3000 milliseconds (or 3 seconds).

Use

Timer functions are used to schedule the execution of code. They can be used for a variety of purposes, such as:

  • To perform cleanup tasks after a specific interval of time
  • To periodically update data from a database or web service
  • To schedule a task that should be executed at a specific time, such as sending out an email or generating a report

Important Points

  • Timer functions are non-blocking, meaning that the code will continue to execute while the timer functions are running.
  • setInterval() and setTimeout() are "inaccurate", meaning that their execution time is not guaranteed to be exact due to the event loop's processing time.
  • Using setImmediate() is preferable to using setTimeout() with a delay of 0 for immediate execution, as setImmediate() is optimized for that use case.

Summary

In this tutorial, we discussed the timer functions available in Node.js, including setTimeout(), setInterval(), and setImmediate(). We covered the syntax, example, output, explanation, use, and important points of timer functions in Node.js. With this knowledge, you can now use Node.js timer functions to schedule the execution of code at a specific interval or time.

Published on: