bugl
bugl
HomeLearnPatternsSearch
HomeLearnPatternsSearch

Loading lesson path

Learn/Node.js/Core Modules
Node.js•Core Modules

Node.js Timers Module

Concept visual

Node.js Timers Module

push / pop from the top({[← top

What is the Timers Module?

The Timers module provides functions that help schedule code execution at specific times or intervals. Unlike browser JavaScript, Node.js timing functions are provided as part of the Timers module, though they are available globally without requiring an explicit import.

Key features include:

Delayed execution with setTimeout()

Repeated execution with setInterval()

Immediate execution in the next event loop with setImmediate()

Promise-based APIs for modern async/await patterns

These capabilities are essential for building responsive applications, implementing polling, handling delayed operations, and more.

Getting Started with Timers

Here's a quick example of using the Timers module to schedule code execution:

Basic Timer Example

const { setTimeout, setInterval, setImmediate } = require('timers');
console.log('Starting timers...');
// Execute once after delay setTimeout(() => {
console.log('This runs after 1 second');
}, 1000);
// Execute repeatedly at interval let counter = 0;
const interval = setInterval(() => {
counter++;
console.log(`Interval tick ${counter}`);
if (counter >= 3) clearInterval(interval);
}, 1000);
// Execute in the next event loop iteration setImmediate(() => {
console.log('This runs in the next iteration of the event loop');
});
console.log('Timers scheduled');

Using the Timers Module

The Timers module's functions are available globally, so you don't need to require them explicitly. However, if you want to access advanced features or for clarity, you can import the module:

const timers = require('timers');
// Or, for the promises API (Node.js 15.0.0+)
const timersPromises = require('timers/promises');
setTimeout() and clearTimeout()
The setTimeout() function schedules execution of a callback after a specified amount of time (in milliseconds).

It returns a

Timeout object that can be used to cancel the timeout.

Common Use Cases

Delaying execution of non-critical tasks

Implementing timeouts for operations

Breaking up CPU-intensive tasks

Implementing retry logic

// Basic usage setTimeout(() => {
console.log('This message is displayed after 2 seconds');
}, 2000);
// With arguments setTimeout((name) => {
console.log(`Hello, ${name}!`);
}, 1000, 'World');
// Storing and clearing a timeout const timeoutId = setTimeout(() => {
console.log('This will never be displayed');
}, 5000);
// Cancel the timeout before it executes clearTimeout(timeoutId);
console.log('Timeout has been cancelled');

Promise-Based setTimeout

Formula

Node.js 15.0.0 and later provide a promises - based API for timers:
const { setTimeout } = require('timers/promises');
async function delayedGreeting() {
console.log('Starting...');
// Wait for 2 seconds await setTimeout(2000);
console.log('After 2 seconds');
// Wait for 1 second with a value const result = await setTimeout(1000, 'Hello, World!');
console.log('After 1 more second:', result);
}
delayedGreeting().catch(console.error);
setInterval() and clearInterval()
The setInterval() function calls a function repeatedly at specified intervals (in milliseconds).

It returns an

Interval object that can be used to stop the interval.

Common Use Cases

Polling for updates

Running periodic maintenance tasks

Implementing heartbeat mechanisms

Updating UI elements at regular intervals

Note:

The actual interval between executions may be longer than specified if the event loop is blocked by other operations.

// Basic interval let counter = 0;
const intervalId = setInterval(() => {
counter++;
console.log(`Interval executed ${counter} times`);
// Stop after 5 executions if (counter >= 5) {
clearInterval(intervalId);
console.log('Interval stopped');
}
}, 1000);
// Interval with arguments const nameInterval = setInterval((name) => {
console.log(`Hello, ${name}!`);
}, 2000, 'Node.js');
// Stop the name interval after 6 seconds setTimeout(() => {
clearInterval(nameInterval);
console.log('Name interval stopped');
}, 6000);

Promise-Based setInterval

Using the promises API for intervals:

const { setInterval } = require('timers/promises');
async function repeatedGreeting() {
console.log('Starting interval...');
// Create an async iterator from setInterval const interval = setInterval(1000, 'tick');
// Limit to 5 iterations let counter = 0;
for await (const tick of interval) {
console.log(counter + 1, tick);
counter++;
if (counter >= 5) {
break; // Exit the loop, stopping the interval
}
}
console.log('Interval finished');
}
repeatedGreeting().catch(console.error);
setImmediate() and clearImmediate()
The setImmediate() function schedules a callback to run in the next iteration of the event loop, after I/O events but before timers.
It's similar to using setTimeout(callback, 0)

but more efficient.

When to Use setImmediate()

When you want to execute code after the current operation completes

Formula

To break up long - running operations into smaller chunks
To ensure callbacks run after I/O operations complete
In recursive functions to prevent stack overflows console.log('Start');
setTimeout(() => {
console.log('setTimeout callback');
}, 0);
setImmediate(() => {
console.log('setImmediate callback');
});
process.nextTick(() => {
console.log('nextTick callback');
});
console.log('End');

The execution order will typically be:

Previous

Node.js Crypto Module

Next

Node.js DNS Module