Timing features in Node.js


The timer module in Node.js consists of different functions that can control and alter the timings of code execution. In this article, we will see how to use some of these functions.

setTimeout() Method

The setTimeout() method schedules the code execution after a designated amount of milliseconds. Only after the timeout has occurred, the code will be executed. The specified function will be executed only once. This method returns an ID that can be used in clearTimeout() method.

Syntax

setTimeout(function, delay, [args])

Parameters

The parameters are defined below:

  • function − This parameter takes input for the function that will be executed.
  • delay − This is the time duration after which the function will be executed.
  • args − Holds any optional arguments.

Example 

 Live Demo

let str = 'TutorialsPoint!';

setTimeout(function () {
   // Will be printed after 2 seconds
   return console.log(str);
}, 2000);

// This will be printed immediately
console.log('Executing setTimeout() method');

Output

C:\home
ode>> node timeout.js Executing setTimeout() method TutorialsPoint!

setImmediate() Method

The setImmediate() method executes the code at the end of the current event loop cycle. The function passed in the setImmediate() argument is a function that will be executed in the next iteration of the event loop.

Syntax

setImmediate(function, [args])

Example

immediate.js

 Live Demo

// Setting timeout for the function
setTimeout(function () {
   console.log('setTimeout() function running');
}, 5000);

// Running this function immediately before any other
setImmediate(function () {
   console.log('setImmediate() function running');
});

// Directly printing the statement
console.log('Simple statement in the event loop');

Output

C:\home
ode>> node immediate.js Simple statement in the event loop setImmediate() function running setTimeout() function running

setInterval() Method

The setInterval() method executes the code after the specified interval. The function is executed multiple times after the interval has passed. The function will keep on calling until the process is stopped externally or using code after specified time period.

Syntax

setInterval(function, delay, [args])

Example

interval.js

 Live Demo

setInterval(function() {
   console.log('Tutoirals Point - SIMPLY LEARNING !');
}, 1000);

Output

C:\home
ode>> node interval.js Tutoirals Point - SIMPLY LEARNING ! Tutoirals Point - SIMPLY LEARNING ! Tutoirals Point - SIMPLY LEARNING ! Tutoirals Point - SIMPLY LEARNING ! Tutoirals Point - SIMPLY LEARNING ! Tutoirals Point - SIMPLY LEARNING ! ^C // Stopped externally using Ctrl+C

Updated on: 16-Aug-2021

475 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements