0
0
Node.jsframework~5 mins

setTimeout and clearTimeout in Node.js

Choose your learning style9 modes available
Introduction

setTimeout lets you run a task after waiting some time. clearTimeout stops that task if you change your mind.

You want to show a message after 3 seconds.
You want to delay a function to avoid running it too fast.
You want to cancel a delayed action if the user clicks a button.
You want to schedule a reminder but allow canceling it.
You want to simulate waiting for something in a simple way.
Syntax
Node.js
const timerId = setTimeout(() => {
  // code to run after delay
}, delayInMilliseconds);

clearTimeout(timerId);

setTimeout returns an ID you use to cancel it with clearTimeout.

The delay is in milliseconds (1000 ms = 1 second).

Examples
This prints a message after 2 seconds.
Node.js
setTimeout(() => {
  console.log('Hello after 2 seconds');
}, 2000);
This schedules a message but cancels it immediately, so nothing prints.
Node.js
const id = setTimeout(() => {
  console.log('This will not run');
}, 3000);
clearTimeout(id);
This calls the greet function with 'Alice' after 1 second.
Node.js
function greet(name) {
  console.log(`Hi, ${name}!`);
}
setTimeout(greet, 1000, 'Alice');
Sample Program

This program starts, schedules a message after 1 second, but cancels it immediately. So only 'Start' and 'End' print.

Node.js
console.log('Start');

const timer = setTimeout(() => {
  console.log('This runs after 1 second');
}, 1000);

clearTimeout(timer);

console.log('End');
OutputSuccess
Important Notes

If you don't call clearTimeout, the scheduled code will run after the delay.

You can use clearTimeout anytime before the delay ends to stop the task.

setTimeout is useful for simple delays but not for precise timing or repeated tasks (use setInterval for repeats).

Summary

setTimeout runs code after a delay.

clearTimeout stops the scheduled code before it runs.

Use the ID from setTimeout to cancel with clearTimeout.