Sometimes you want your code to run after some time. In such cases, the core Timers module in Node.js is the best option.
While browsing the web, you should see many places where you get events on a web page after a set amount of time. It can be a pop-up message, a notification, or a sound and the list is endless.
In this tutorial, we will learn about the Timers module and its function that can make this happen!
The Timers come with functions such as setTimeout, setInterval, setImmediate, clearTimeout, clearInterval and clearImmediate which we will cover throughout the guide, each with their syntax, parameter and an example.
What is the Timers Module in Node.js?
Timers module in Node.js comes with functions that execute code after a set time. This does not require importing using the require(). This is because all functions on this module are made available globally to imitate the browser’s JavaScript API.
Learn more about the Require in Node.js.
Adjusting the Time Continuum with Node.js
The Timer API in Node.js features a number of methods that allow a developer to schedule the execution of code at any time after the current moment.
The functions that we will tell you about will seem familiar because of the similarity in all browsers. However, Node has its own way of implementing these functions.
Although the Timers module is closely integrated into the system and emulates the browser API, there are many differences in their implementation.
Let us now look at the functions under this module one by one.
1. setTimeout & clearTimeout
The setTimeout() Function – “When I say so” or “At this point” Execution
The setTimeout() function is used when you want to execute your code at a given time, in milliseconds. This function works similarly to window.setTimeout() from the browser’s JS API, but a string of code cannot be passed.
This asynchronous function accepts a callback as its first argument and a delay as the second function argument in milliseconds as a number. We may also pass additional optional arguments that would be passed to the callback.
Syntax:
setTimeout(callback[, delay[, ...args])
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
Let us elucidate the concept with an example.
Example:
// A constant function 'sayHello' that takes a 'name' parameter
const sayHello = (name) => {
console.log(`Hello, ${name}`);
}
// Use setTimeout to delay the execution of 'sayHello' function by 10 sec
setTimeout(sayHello, 10000, 'Sloan');
Here, the sayHello() will be added to the execution queue and executed as soon as the 10000 milliseconds (10 seconds) 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.
The clearTimeout() Function – 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 behaviour.
Syntax:
clearTimeout(timeout)
Let us tweak our example a little bit so you can understand it better.
Example:
// A constant function to log a msg after 10 sec
const sayHello = setTimeout(function(name) {
console.log(`Hello, ${name}`);
}, 10000, 'Sloan'); //
// Clear the timeout to stop the execution of 'sayHello' function
clearTimeout(sayHello);
This will now clear the timer set for the sayHello() function and the message will be logged on the console immediately.
2. setInterval & clearInterval
The setInterval() Function – “Infinite Loop” or “After every” Execution
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, specified in the second argument.
Syntax:
setInterval(callback[, delay[, ...args]])
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
Below is the JavaScript code example to demonstrate this.
Example:
// A constant function using setInterval to log a msg every 3 sec
const alertMessage = setInterval(function() {
console.log(`You have a message!`);
}, 3000);
After this, the alert message function is executed every 3000 milliseconds (3 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.
The clearInterval() Function – Clearing the Interval
The clearInterval() function clears the delays set by the setInterval(), meaning that the code 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 behaviour.
Syntax:
clearInterval(timeout)
Example:
// A constant function using setInterval to log a msg every 3 sec
const alertMessage = setInterval(function() {
console.log(`You have a message!`);
}, 3000);
// Clear the interval to stop the execution of 'alertMessage' function
clearInterval(alertMessage);
Doing this will now stop the execution of the code.
3. setImmediate & clearImmediate
The setImmediate() Function – “Right after this” Execution
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.
Syntax:
setImmediate(callback[,...args])
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
Example:
// A function using setImmediate to print a msg
var greetUser = setImmediate(function(name) {
console.log(`Hey, ${name}`);
});
The clearImmediate() Function – Clearing the Immediate
The setImmediate() function returns an Immediate object which can be used to cancel the scheduled setImmediate() function.
Syntax:
clearImmediate(immediate)
Example:
Let’s look at an example:
// A function using setImmediate to print a msg
var greetUser = setImmediate(function(name) {
console.log(`Hey, ${name}`);
});
// Clear the immediate to stop the execution of 'greetUser' function
clearImmediate(greetUser);
The scheduled setImmediate() will now be cancelled.
Read More:
Conclusion
In this tutorial, we have learned to delay the execution of the code using setTimeout, setInterval, and setImmediate functions in Node.js, all of which are asynchronous. These functions execute later or repeatedly but do not block the execution of the rest of the code. Instead, they send the functions to the Node.js event loop and run after the specified timeout. Since each of the functions are a bit similar, it is important to remember when to use which, you can create a simple Node.js application and use all of them to wrap up the concept. At last, we hope you have enjoyed reading the content.
Reference
https://nodejs.org/en/docs/guides/timers-in-node