Timers in NodeJs
There are several ways to create timers in Node.js, including using the setTimeout()
and setInterval()
functions from the timers
module.
setTimeout()
is used to execute a function once after a specified amount of time has passed.
Example:
setTimeout(() => {
console.log('Hello, World!');
}, 1000);
This will print "Hello, World!" to the console after 1000 milliseconds (1 second) have passed.
setInterval()
is used to execute a function repeatedly, at a specified interval.
Example:
setInterval(() => {
console.log('Hello, World!');
}, 1000);
This will print "Hello, World!" to the console every 1000 milliseconds (1 second).
Both functions return a timeoutId you can use to clear the timer if you need to.
const timeoutId = setTimeout(() => {
console.log('Hello, World!');
}, 1000);
clearTimeout(timeoutId);
const intervalId = setInterval(() => {
console.log('Hello, World!');
}, 1000);
clearInterval(intervalId);
You can also use setImmediate()
that will trigger the callback in the next iteration of the event loop, useful when you don't know how long your operation will take.
Additionally, you can use promise
and async/await
to create timer.
const delay = (ms) => new Promise(resolve => setTimeout(resolve, ms));
const delayedHello = async () => {
console.log('Starting...');
await delay(3000);
console.log('Hello, World!');
}
These are just a few examples of how timers can be used in Node.js. There are many other ways to create and use timers in Node.js, depending on the specific needs of your application.
Thanks for reading ❤️ Hope you learned something
Any other inputs or recommendations feel free to share below
Subscribe to my newsletter
Read articles from Dhanush N directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by
Dhanush N
Dhanush N
Experienced Consultant, Full Stack Developer, R&D Engineer who loves to solve puzzles & technology problems by code/