How to Use Timers in Node.JS

Read it in 7 Mins

Last updated on
12th Jan, 2022
Published
04th Jan, 2022
Views
2,555
How to Use Timers in Node.JS

You can use Node.js's utilities to schedule the execution of your code. The timer module, unlike most Node.js modules, is not imported. To comply with the JavaScript browser API, the methods are globally accessible.

The Node.js Timers module contains several functions that allow you to execute a block of code or a function after a specified amount of time. You don't need to use require() to import the Timers module because it's global.

In this post, I'll explain and demonstrate what timers are, how to use them, how the syntax looks, and how you can use them in your applications. For example, if you want to retrieve data from a REST API at a specific interval, you can easily do so with timers. So, even if you are unfamiliar with JavaScript or timers, this post will help you understand these concepts.

The Event Loop - A Quick Primer

Node.js is a single-threaded, event-driven platform that can run non-blocking, asynchronous code. These Node.js features make it memory efficient. Even though JavaScript is single-threaded, the event loop enables Node.js to perform non-blocking I/O operations. It is accomplished by delegating tasks to the operating system whenever and wherever possible.

Because most operating systems are multi-threaded, they can handle multiple operations that are running in the background. When one of these operations is finished, the kernel notifies Node.js, and the callback associated with that operation is added to the event queue, where it will eventually be executed.

Features of Event Loop:

  • An event loop is an infinite loop that waits for tasks, executes them, and then sleeps until more tasks are received.
  • When the call stack is empty, i.e., there are no ongoing tasks, the event loop executes tasks from the event queue.
  • We can use callbacks and promises in the event loop.
  • The event loop executes the tasks in reverse order, beginning with the oldest.

Example:

console.log("One");
setTimeout(function(){
console.log("Two");
}, 1000);
console.log("Three");

Output:

One

Three

Two

The first console log statement is pushed to the call stack in the above example, and "One" is logged on the console before the task is popped from the stack. Following that, the setTimeout is added to the queue, the task is sent to the operating system, and the task's timer is set. After that, this task is removed from the stack. The third console log statement is then pushed to the call stack, "Three" is logged on the console, and the task is removed from the stack.

Timers in JavaScript

A timer is used in JavaScript to execute a task or function at a specific time. The timer is essentially used to delay the execution of the program or to execute the JavaScript code at regular intervals. You can delay the execution of the code by using a timer. As a result, when an event occurs or a page loads, the code does not complete its execution at the same time.

Advertisement banners on websites, which change every 2-3 seconds, are the best example of a timer. These advertising banners are rotated at regular intervals on websites such as Flipkart. To change them, you set a time interval.

JavaScript provides two timer functions, setInterval() and setTimeout(), which help to delay code execution and allow one or more operations to be performed repeatedly.

setTimeout():

The setTimeout() function allows users to postpone the execution of code. The setTimeout() method accepts two parameters, one of which is a user-defined function, and the other is a time parameter to delay execution. The time parameter, which is optional to pass, stores the time in milliseconds (1 second = 1000 milliseconds).

setInterval():

The setInterval method is similar to the setTimeout() function in some ways. It repeats the specified function after a time interval. Alternatively, you can say that a function is executed repeatedly after a certain amount of time specified by the user in this function.

Timers in Node.js - setTimeout()

setTimeout() can be used to execute code after a specified number of milliseconds. This function is equivalent to window. setTimeout() from the browser JavaScript API, but no code string can be passed to be executed.

setTimeout() takes a function to execute as the first argument and a millisecond delay defined as a number as the second. Additional arguments may be provided, and these will be passed to the function. As an example, consider the following:

Using setTimeout()

The timeout interval is not guaranteed to execute after that exact number of milliseconds. This is because any other code that blocks or holds onto the event loop will delay the execution of the timeout. The only guarantee is that the timeout will not be executed sooner than the timeout interval specified.

setTimeout(function A() { 
    return console.log('Hello World!'); 
}, 2000); 
console.log('Executed before A');

How to use Timers in Node.js

clearTimeout():

The clearTimeout() method deactivates a timer that was previously set with the setTimeout() method.

The ID value returned by setTimeout() is passed to the clearTimeout() method as a parameter.

Syntax:

clearTimeout(id_of_settimeout)

Example: 

function welcome () {   
    console.log("Welcome to Knowledgehut!");   
  }   
  var id1 = setTimeout(welcome,1000);   
  var id2 = setInterval(welcome,1000);   
  clearTimeout(id1);

How to use Timers in Node.js

Timers in Node.js - setImmediate()

To execute code at the end of the loop cycle, use the setImmediate() method. In layman's terms, this method divides tasks that take longer to complete, in order to run a callback function that is triggered by other operations such as events.

Syntax:

let immediateId = setImmediate(callbackFunction, [param1, param2, ...]);
let immediateId = setImmediate(callbackFunction);

The function to be executed will be the first argument to setImmediate(). When the function is executed, any additional arguments will be passed to it.

Now consider the difference between setImmediate() and process. nextTick(), as well as when to use which.

While processing, setImmediate() is executed in the Check handlers phase. process.nextTick() is called at the start of the event loop and at the end of each phase.

process.nextTick() has higher priority than setImmediate():

setImmediate(() => console.log('I run immediately')) 
process.nextTick(() => console.log('But I run before that'))

Output:

How to use Timers in Node.js

Using setImmediate()

Multiple setImmediate functions are called in the following example. When you do this, the callback functions are queued for execution in the order in which they are created. After each event loop iteration, the entire callback queue is processed. If an immediate timer is queued from within an executing callback, it will not be triggered until the next iteration of the event loop.

Example:

setImmediate(function A() { 
    setImmediate(function B() { 
      console.log(1); 
      setImmediate(function D() {   
        console.log(2); 
      }); 
    }); 

    setImmediate(function C() { 
      console.log(3); 
      setImmediate(function E() {   
        console.log(4); 
      }); 
    }); 
}); 
console.log('Started');

How to use Timers in Node.js

clearImmediate():

The clearImmediate function is used to remove the function call that was scheduled by the setImmediate function. Both of these functions can be found in Node.js's Timers module.

Example:

console.log("Before the setImmediate call") 
let timerID = setImmediate(() => {console.log("Hello, World")}); 
console.log("After the setImmediate call") 
clearImmediate(timerID);

How to use Timers in Node.js

Timers in Node.js - setInterval()

This method, unlike setTimeout(), is used to execute code multiple times. For example, the company may send out weekly newsletters to its Edge as a Service customer. This is where the setInterval() method comes into play. It is an infinite loop that will continue to execute as long as it is not terminated (or halted).

As the second argument, setInterval() accepts a function argument that will run an infinite number of times with a given millisecond delay. In the same way that setTimeout() accepts additional arguments beyond the delay, these will be passed on to the function call. The delay, like setTimeout(), cannot be guaranteed due to operations that may stay in the event loop and should thus be treated as an approximation.

Syntax:

let intervalId = setInterval(callbackFunction, [delay, argument1, argument2, ...]); //option 1
let intervalId = setInterval(callbackFunction[, delayDuration]); // option 2
let intervalId = setInterval(code, [delayDuration]); //option 3

Using setInterval()

Example:

setInterval(function A() { 
    return console.log('Hello World!'); 
}, 1000); 

// Executed right away 
console.log('Executed before A');

How to use Timers in Node.js

setInterval(), like setTimeout() returns a Timeout object that can be used to reference and modify the interval that was set.

In the above example, function A() will execute after every 1000 milliseconds.

clearInterval():

Example:

var si = setInterval(function A() { 
    return console.log("Hello World!"); 
}, 1000); 

setTimeout(function() { 
    clearInterval(si); 
}, 4000);

How to use Timers in Node.js

Using Timer.unref()

The timer module is used to schedule functions that will be called later. Because it is a global API, there is no need to import (require("timers")) to use it.

The Timeout Class contains an object (setTimeout()/setInterval()) that is created internally to schedule actions, and (clearTimeout()/clearInterval()) that can be passed to cancel those scheduled actions. When a timeout is set, the Node.js event loop will continue to run until clearTimeout() is called. The setTimeout() method returns timeout objects that can be used to control this default behaviour, and it exports both the timeout.ref() and timeout.unref() functions.

timeout.ref():

When the Timeout is active and (timeout.ref()) is called, it requests that the Node.js event loop not exit for an extended period of time. In any case, calling this Method multiple times has no effect.

Syntax:

timeout.ref()

timeout.unref():

When the Timeout is enabled, the Node.js event loop is not required to remain active. If any other activity keeps the event loop running, the Timeout object's callback is invoked after the process exits. In any case, calling this Method multiple times has no effect.

Syntax:

timeout.unref()

Example:

var Timeout = setTimeout(function alfa() { 
    console.log("0.> Setting Timeout", 12); 
}); 
console.log("1 =>", Timeout.ref()); 
Timeout.unref() 
Timeout.ref() 

console.log("2 =>", Timeout.unref()); 

clearTimeout(Timeout); 
console.log("3 => Printing after clearing Timeout"); 

Output:

How to use Timers in Node.js

Scheduling Made Simpler

In this tutorial, you learned how to schedule tasks with the Node.js timer module. You've seen how to set timeouts, interval timers for recurring tasks, and how to use set immediate to bypass long operations. You've also seen how to stop these operations using the clear() method for each method.

As with learning anything new, practising what you learn will make a big difference to how easily you can perform these tasks. Share your thoughts and questions in the comments as you try out what you’ve learnt.

Profile

Abhresh Sugandhi

Author

Abhresh is specialized as a corporate trainer, He has a decade of experience in technical training blended with virtual webinars and instructor-led session created courses, tutorials, and articles for organizations. He is also the founder of Nikasio.com, which offers multiple services in technical training, project consulting, content development, etc.