MyInternships.in

Asynchronous JavaScript

Node.js Timers setTimeout setInterval

setTimeout schedules a callback once, setInterval repeats it, and setImmediate runs on the next event loop iteration. All three return handles you must clear to avoid keeping the process alive.


What is Timers setTimeout setInterval in Node.js?

setTimeout schedules a callback once, setInterval repeats it, and setImmediate runs on the next event loop iteration. All three return handles you must clear to avoid keeping the process alive.

Timers setTimeout setInterval example

Timers and their promise forms
JavaScript
const t = setTimeout(() => console.log('later'), 1000);
clearTimeout(t);

const i = setInterval(poll, 5000);
clearInterval(i);

// promise-based timers
import { setTimeout as sleep } from 'node:timers/promises';
await sleep(1000);
console.log('one second later');

Key points to remember

  • The delay is a minimum, not a guarantee — a blocked event loop delays it further.
  • An uncleared interval keeps the Node process running forever.
  • unref() lets a timer exist without holding the process open.
  • setInterval can overlap if the callback takes longer than the interval — prefer a self-scheduling setTimeout for polling.

Common mistakes with Timers setTimeout setInterval

  • A polling setInterval whose work takes longer than the interval, stacking overlapping runs.
  • Forgetting clearInterval in a test, so the test runner never exits.

Node.js Timers setTimeout setInterval— Interview Questions & FAQs

Why does my Node script not exit?+

Something is keeping the event loop alive — usually an uncleared setInterval, an open server, or a database connection. Clear timers and close handles, or call unref() on anything that should not block exit.

Related Node.js Topics

Keep learning with these closely related lessons.

Ready to use your Node.js skills?

Find verified Node.js internships and fresher developer jobs across India.

Browse Node.js Internships