Node.js Timers Module: setTimeout, setInterval, setImmediate

There are times when you want your code to run after some time. In such cases, the core Timers module in Node.js is the best option to go with. 

When browsing the web, you must come across so many places where you find events on a web page after a set time. It could be a pop-up message, a notification, a sound, and the list are endless. 

In this tutorial, I am going to walk you through all the functions under the Timers module which can make this happen!

This module comes with functions namely setTimeout, setInterval, setImmediate, clearTimeout, clearInterval, and clearImmediate, which we will cover today. 

What is the Timers Module in Node.js? 

As discussed above, Timers in Node.js comes with functions that run/execute code after a set time. This module does not require importing using the require() module. 

This is because all functions on this module are made available globally to imitate the browser’s JavaScript API. 

Learn more about the Require module in Node.js.

Adjusting the Time Continuum with Node.js 

The Timers API in Node.js facilitates several ways a developer can schedule the code execution of his/her code at any point of time after the present moment. 

The functions that I will be walking you through, would seem familiar because of their commonality across browsers. However, Nodejs has its own ways of implementing these functions. 

Although the Timers module integrates closely into the system and emulates the browser API, there are several differences in their implementation. 

setTimeout & clearTimeout 

setTimeout(callback[, delay[, …args] – “When I say so” or “At this point” Execution 

This is the list of arguments accepted by setTimeout(): 

  • callback – function to execute when the timer elapses 
  • delay – time in milliseconds to wait before executing callback, default = 1 second 
  • …args – optional, arguments to pass when the callback is executed 

The setTimeout() function is used when you want to execute your code at a given time, in milliseconds. This function works similar to window.setTimeout() from the browser’s JS API, but a string of code cannot be passed. 

This function accepts a callback as its first argument and a delay as the second argument in milliseconds as a number. We may also pass additional optional arguments that would be passed to the callback. 

Let us elucidate the concept with an example: 

const sayHello (name) => {

    console.log(`Hello, ${name}`);

}

setTimeout(sayHello, 2000, ‘Sloan’);

Here, our sayHello() method will be executed as soon as the 2000 milliseconds (2 seconds) are elapsed because setTimeout() was called. It is important to keep in mind that the timeout interval cannot be relied upon to run after the exact number of milliseconds. 

This happens usually because some other running code blocks or holds onto the event loop and pushes the execution of the timeout back. 

The guarantee is that the timeout would never be sooner than the set timeout interval. 

clearTimeout(timeout) – Cancelling the Timeout 

The clearTimeout() clears the timer set by the setTimeout(). So, when the code runs, the execution is halted immediately. The setTimeout() basically returns a Timeout object which can be used to cancel the timeout resulting in a change in the execution behavior. 

Let us tweak our example a little bit so you can understand it better: 

const sayHello = setTimeout(function(name) {

    console.log(`Hello, ${name}`);

}, 2000, ‘Sloan’);

clearTimeout(sayHello);

This will now clear the timer set for the sayHello() function and the message will be logged immediately. 

setInterval & clearInterval 

setInterval(callback[, delay[, …args]]) – “Infinite Loop” or “After every” Execution 

This is the list of arguments accepted by setInterval(): 

  • callback – function to execute when the timer elapses 
  • delay – time in milliseconds to wait before executing callback, default = 1 second 
  • …args – optional, arguments to pass when the callback is executed 

If you want a block of code to be executed multiple times after a set interval, then you can make use of the setInterval() function. The arguments accepted by the setInterval() function are similar to those of setTimeout(). 

The callback argument accepted by this function will be executed an infinite number of times with a given delay in milliseconds, passed in the second argument. 

const alertMessage = setInterval(function() {

    console.log(`You have a message!`);

}, 2000);

Now, alert message function will be executed every 2000 milliseconds (2 seconds). Again, the delay cannot be predicted to be exact because of other codes that block the timers in the browser or hold onto the event loop. 

clearInterval(timeout) – Clearing the Interval 

The clearInterval() function clears the delays set by the setInterval(), meaning which the code is execution is halted completely. The setInterval() also returns a Timeout object which can be used to cancel the interval delays resulting in a change in the execution behavior. 

const alertMessage = setInterval(function() {

    console.log(`You have a message!`);

}, 2000);

clearInterval(alertMessage);

Doing this will now stop the execution of the code. 

setImmediate & clearImmediate 

setImmediate(callback[,…args]) – “Right after this” Execution 

This is the list of arguments accepted by setInterval(): 

  • callback – function to execute when the timer elapses 
  • …args – optional, arguments to pass when the callback is executed 

When you want to run a block of code asynchronously, but as soon as possible, you can make use of the setImmediate() function. 

This function can be used to break up long-running operations and execute the callback functions immediately once the browser completes other operations. 

const greetUser = setImmediate(function(name) {

    console.log(`Hey, ${name}`);

}

clearImmediate(immediate) 

The setImmediate() function returns an Immediate object which can be used to cancel the scheduled setImmediate() function. 

Let’s look at an example: 

const greetUser = setImmediate(function(name) {

    console.log(`Hey, ${name}`);

}

clearImmediate(greetUser);

The scheduled setImmediate() will now be canceled. 

Conclusion 

When programming in Node.js, you would come across times when you want your code to run after time or for some time. In such cases, the core Timers module in Node.js is the best option to go with.

Noteworthy References 

Aneesha S
Aneesha S
Articles: 175