Using Node.js Timers: Scheduling Code Execution with `setTimeout()` and `setInterval()`
Learn how to use Node.js's built-in timer functions (`setTimeout()` and `setInterval()`) to schedule code execution after a specified delay or at regular intervals. This tutorial provides clear examples and explains how to manage timers effectively for creating dynamic and responsive applications.
Node.js Timers
Node.js provides global timer functions that don't require the `require()` statement. These functions allow you to schedule code execution after a specified delay or at regular intervals.
Timer Functions
Node.js offers these timer functions:
Setting Timers
setImmediate()
: Executes a callback function after the current event loop iteration completes.setInterval()
: Repeatedly executes a callback function at a specified interval (in milliseconds).setTimeout()
: Executes a callback function once after a specified delay (in milliseconds).
Clearing Timers
clearImmediate(immediateObject)
: Cancels a timer set bysetImmediate()
.clearInterval(intervalObject)
: Cancels a timer set bysetInterval()
.clearTimeout(timeoutObject)
: Cancels a timer set bysetTimeout()
.
Example: setInterval()
This example prints a message every 1000 milliseconds (1 second):
setInterval Example
setInterval(function() {
console.log("setInterval: Hey! 1 second completed!..");
}, 1000);
Run this with node timer1.js
. The script will continue running until you manually stop it.
Here's another example that increments a counter every second:
setInterval Example with Counter
var i = 0;
console.log(i);
setInterval(function() {
i++;
console.log(i);
}, 1000);
Example: setTimeout()
This example prints a message after a 1-second delay:
setTimeout Example
setTimeout(function() {
console.log("setTimeout: Hey! 1 second completed!..");
}, 1000);
Run with node timer1.js
. The message is printed once after the delay.
This example uses recursion to repeatedly call setTimeout:
Recursive setTimeout
var recursive = function() {
console.log("Hey! 1 second completed!..");
setTimeout(recursive, 1000);
};
recursive();
Example: Using clearTimeout() and clearInterval()
These examples demonstrate canceling timers:
clearTimeout() Example
function welcome() {
console.log("Welcome to JavaTpoint!");
}
var id1 = setTimeout(welcome, 1000);
var id2 = setInterval(welcome, 1000);
clearTimeout(id1); // Cancel setTimeout
// clearInterval(id2); //Uncomment to cancel setInterval
clearInterval() Example
function welcome() {
console.log("Welcome to JavaTpoint!");
}
var id1 = setTimeout(welcome, 1000);
var id2 = setInterval(welcome, 1000);
// clearTimeout(id1); //Uncomment to cancel setTimeout
clearInterval(id2); // Cancel setInterval
next →
← prev