Skip to main content

Command Palette

Search for a command to run...

Timers in NodeJs

NodeJs Part 6

Updated
2 min read
Timers in NodeJs
D

Experienced Consultant, Full Stack Developer, R&D Engineer who loves to solve puzzles & technology problems by code/

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

Follow me via Twitter, Github, Instagram

Node.js Concepts

Part 6 of 8

In this series I will be writing about node js concepts in form of minimal blogs which would help you in understanding the various concepts of node.js

Up next

Concurrent programming in NodeJs

NodeJs Part 7

More from this blog

Dhanush N

56 posts

Experienced Consultant & Software Engineer with experience around building and scaling applications over various emerging technologies. I love solving puzzles & provide technological solutions by code