Updated March 31, 2023
Introduction to Node.js Timer
Ever been in a situation where you have to execute a piece of code after a length of time that has passed or maybe execute it repeatedly after a particular interval of time. Well, Node.js introduces a solution to this in the form of timers. Node.js timer gives us the privilege to execute code immediately as soon as the event loop is active, after a particular specified time, or maybe after a particular set of intervals. In this topic, we are going to learn about Node.js Timer.
Node.js Timers
In Node.js we have objects that can directly be used in our application. Those objects are called as global objects. As these objects are global, they are accessible from anywhere.
One of these global objects is Nodejs timers. We don’t need to explicitly use the require() method to include the timers of Nodejs in our web application. Node.js introduces various timer functions, for example, setTimeout() method allows you to execute a particular code after a specified time while the setInterval() method gives the privilege to keep executing a code block after specific intervals of time. The setImmediate() method allows executing the code block as soon as the Nodejs event loop is active. We will also look into the other methods that let us destroy the objects created by the Nodejs timers.
Node.js Timer Functions
Let us look after the various timer functions and its implementation in Node.js:
1. setTimeout()
setTimeout() method is used to execute a piece of code after a specified time. It takes the first argument as a function and the second argument as time in milliseconds. The code will be executed after the time that is passed as the argument.
Demonstration of setTimeout method()
Code:
setTimeout(callBack, 10000)
function callBack(){
console.log("This message is from setTimeout method")
}
Output:
According to the above code, the console.log() written in the callback function will execute after 10000 milliseconds, i.e 10 seconds.
2. clearTimeout()
The clearTimeout() method allows us to destroy/ cancel the timer created by the setTimeout object. The setTimeout() methods returns an id (number) which is stored in a variable and that variable is passed to clearTimeout() method which clears the timer.
The object returned when the timeout is scheduled, it exports the timeout.ref() and timeout.unref() functions that help us control the behavior.
The timeout.hasRef() method, it returns true; the timeout object keeps the Event Loop active. The timeout.ref() method returns the reference to timeout and requests node not to exit the Event Loop as long as the timeout object is active and the timeout.unref() method on being called will not require the Nodejs Event Loop to remain active. The timeout.refresh() method allows refreshing a timer without allocating a new Javascript object.
Demonstration of clearTimeout() method
Code:
var timeoutObject;
timeoutObject = setTimeout(callBack, 10000)
function callBack(){
console.log("This message is from setTimeout method")
}
function stopTimeout(){
clearTimeout(timeoutObject)
}
Output:
3. setImmediate()
setImmediate() method queues its callback on the event loop and any function that is passed to setImmediate method() is executed in the next iteration of the event loop.
The first argument passed to the setImmediate() method is a function that will be executed and setTimeout() with 0ms is similar to setImmediate().
Demonstration of setImmediate() method
Code:
setImmediate(printSomething) function printSomething(){
console.log('This message is displayed immediately by setImmediate()')
}
Output:
The above console.log() is printed as soon as the code is executed.
4. clearImmediate()
The clearImmediate() method is used to cancel /destroy the object which is created by the setImmediate() method.
The object returned when the immediate is scheduled, it exports the immediate.ref() and immediate.unref() functions that help us control the behavior.
The immediate.hasRef() method, it returns true; the immediate object keeps the Event Loop active. The immediate.ref() method returns the reference to immediate and requests node not to exit the Event Loop as long as the immediate
object is active and the immediate.unref() method on being called will not require the Nodejs Event Loop to remain active.
Demonstration of clearImmediate() method
Code:
var immediateObject;
immediateObject = setImmediate(printSomething) function printSomething(){
console.log('This message is displayed immediately by setImmediate()')
}
function stopImmediateObject(){ clearImmediate(immediateObject)
}
Output:
5. setInterval()
The setInterval() method gives the privilege to keep executing a piece of code after a particular period of time. It takes the first argument as the callback function and the second argument is the time in milliseconds.
Demonstration of setInterval() method
Code :
setInterval(printSomeStuff, 5000) function printSomeStuff(){
console.log('This message is displayed from setInterval method')
}
Output :
The below code will keep on printing the statement present in console.log() after every 5000 milliseconds i.e 5 seconds.
6. clearInterval()
The clearInterval() method is used to cancel the object created by the setInterval method().
Demonstration of clearInterval() method
Code:
var intervalObject;
intervalObject = setInterval(printSomeStuff, 5000) function printSomeStuff(){
console.log('This message is displayed from setInterval method')
}
function stopIntervalObject(){ clearInterval(intervalObject)
}
Output:
Uses of Node.js Timers
- One of the usecase where Nodejs timer can be used is for clearing the session data once the user is logged out of our web application.
- It can be also used while closing the database connections before exiting Node.js.
- For receiving results from an API, timers can be used.
- Timers can also be used for error handling in Node.js.
Conclusion
Thus we studied about the Node.js timers. We went through the various timer functions like setImmediate(), setTimeout() and setInterval() and functions like clearImmediate(), clearTimeout() and clearInterval() which destroys the objects created by the Node.js timers.
Recommended Articles
This is a guide to Node.js Timer. Here we discuss the various timer functions and their demonstrations along with the codes and outputs. You may also have a look at the following articles to learn more –