How to use Timers in Node.js?

If you want to execute after set period of time, timers are used for that. Timers are globally available in node.js. Check official documentation here.

Three types of timers are:

  • setTimeout()
  • setImmediate()
  • setInterval();
  1. setTimeout() – “When I say so!”
  • used for scheduling execution of code after set of milliseconds.
  • accepts set of arguments – first arg. is a function, second arg. is a time in milliseconds. You can also pass extra args also.
function myFunction(arg) {
  console.log(`The arg was => ${arg}`);
}

setTimeout(myFunction, 2500, 'thewebspark');

Above function myFunction() will execute as close to 2500 milliseconds (or 2.5 seconds) as possible due to the call of setTimeout()


2. setImmediate() – “Right after this!”

  • It will execute code after completion of current event loop cycle.
  • “right after this”, meaning any code following the setImmediate() function call will execute before the setImmediate() function argument.
console.log('before immediate');
function myFunction(arg){
console.log("after everything" +args);
}

setImmediate(myFunction, 'so immediate');

console.log('after immediate')

Output:

seimme


3. setInterval() – “Infinite Loop Execution”

  • executes block of code multiple set of times.
  • setInterval() takes a function argument that will run an infinite number of times with a given millisecond delay as the second argument.
  • myFunction() will execute about every 2500 milliseconds, or 2.5 seconds, until it is stopped
function myFunction() {
  console.log('I am unstoppable!');
}

setInterval(myFunction, 2500);
Advertisement

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s