QA
Beginner LevelNode JS

How do timers work in Node.js (setTimeout, setInterval, unref, ref)?

❓ Interview Prompt: Explain setTimeout, setInterval, clearTimeout, clearInterval, and unref()/ref() preventing process exit.

Timers in Node.js mirror browser APIs but include server-specific control methods:

•
'timer.unref()': Allows the Node.js event loop to exit even if the timer is still active!
•
'timer.ref()': Re-activates a previously unref'd timer to keep the process alive.

Code Implementation Example

javascript
const timer = setInterval(() => {
  console.log('Background heartbeat check...');
}, 5000);

// Prevent this interval timer from keeping the Node.js process alive on exit!
timer.unref();
💡Using timer.unref() to allow Node.js process exit despite active timers.
🎯 Interview Key Takeaway

Call timer.unref() on background timers to allow the Node.js process to exit cleanly when main work finishes.

#Timers#setTimeout#unref#Beginner
Back to all Node JS Questions→

More Node JS Interview Questions

Beginner LevelNode JS

How does the Node.js Event Loop work? Explain the 6 execution phases (Timers, Pending, Poll, Check, Close).

Beginner LevelNode JS

What does 'Single-Threaded, Event-Driven, Non-Blocking I/O' mean in Node.js?

Beginner LevelNode JS

What is the difference between process.nextTick() and setImmediate()?