Node.js applications often use timers to run background tasks, schedule callbacks, refresh data, or perform periodic checks. These timers are useful, but they can also affect when an application shuts down.
By default, an active timer keeps the Node.js event loop running. This means that even when an application has finished its main work, a pending timer can prevent the process from exiting. In some situations, this is exactly what we want. In others, it creates unnecessary delays during application shutdown.
Node.js provides two methods to control this behavior: ref() and unref(). These methods allow developers to decide whether a timer should keep the process alive. They are available on the Timeout objects returned by setTimeout() and setInterval(), as well as the Immediate objects returned by setImmediate().
Understanding these methods helps developers build background tasks, command-line tools, monitoring processes, and server applications that shut down more predictably.
Why Timers Can Keep a Node.js Process Running
Node.js uses an event loop to manage asynchronous operations. It processes callbacks when timers expire, I/O operations complete, and other asynchronous activities become ready.
The event loop also determines when a Node.js process can exit. If active resources still require the process to remain available, Node.js continues running.
Consider a simple example:
console.log("Application started");
setTimeout(() => {
console.log("Background task completed");
}, 10000);
console.log("Main task completed");
The application prints the first and third messages immediately. However, it does not exit immediately because the scheduled timeout is still active.
After approximately ten seconds, the timer callback executes, and the process can exit if no other active resources remain.
This behavior is useful when the timer represents important work that must finish. However, it may not be necessary for optional background operations such as periodic metrics collection, cache refresh attempts, or non-critical cleanup.
The important point is that scheduling a timer does more than register a callback. By default, it also creates a reason for the Node.js process to remain active.
Understanding ref() and unref()
The ref() and unref() methods control whether a timer or immediate operation keeps the Node.js event loop active.
What Does ref() Do?
The ref() method tells Node.js that the scheduled operation should keep the event loop running until it completes or is cancelled.
Timers created through setTimeout() and setInterval() are referenced by default. The same applies to Immediate objects created through setImmediate().
For example:
const timer = setTimeout(() => {
console.log("Important operation completed");
}, 5000);
timer.ref();
console.log("Timer is keeping the process alive");
Calling ref() explicitly is unnecessary here because the timer is already referenced. However, it becomes useful when an operation was previously unreferenced and you later decide that it must keep the process running.
For example:
const timer = setTimeout(() => {
console.log("Scheduled operation completed");
}, 5000);
timer.unref();
// Later, the operation becomes important.
timer.ref();
After ref() is called, the timer once again prevents the process from exiting while it remains active.
What Does unref() Do?
The unref() method tells Node.js that the scheduled operation should not keep the event loop running.
Consider the following example:
console.log("Application started");
setTimeout(() => {
console.log("This message may not appear");
}, 10000).unref();
console.log("Application completed");
The timeout is still scheduled, but it no longer prevents the process from exiting.
Because there is no other active work keeping the event loop running, Node.js can exit before the ten-second timeout expires. As a result, the callback may never execute.
This is the main purpose of unref(): it allows optional background operations to run when the process is active without forcing the application to stay alive just to execute them.
It does not cancel the timer or guarantee that the callback will be skipped. If other active resources keep the process running long enough, the callback can still execute.
Checking Timer Reference Status With hasRef()
Node.js also provides hasRef() to check whether a timer or immediate currently keeps the event loop active.
The method returns a Boolean value:
- true means the operation is referenced and keeps the event loop active.
- false means the operation is unreferenced and does not keep the event loop active.
For example:
const timer = setTimeout(() => {
console.log("Timer completed");
}, 5000);
console.log(timer.hasRef()); // true
timer.unref();
console.log(timer.hasRef()); // false
timer.ref();
console.log(timer.hasRef()); // true
This method is useful when debugging timer behavior or building reusable utilities that need to inspect their current lifecycle state.
The same method is available on Immediate objects returned by setImmediate().
Using unref() With setTimeout()
A one-time timeout is commonly used for delayed operations such as retry attempts, temporary notifications, cleanup tasks, and scheduled checks.
When the operation is optional, unref() can prevent it from unnecessarily extending the application's lifetime.
For example, consider a command-line application that performs its main task and schedules a non-critical cleanup operation.
function runApplication() {
console.log("Processing application data");
setTimeout(() => {
console.log("Performing optional cleanup");
}, 15000).unref();
console.log("Main operation completed");
}
runApplication();
If the main operation finishes and no other active resources remain, the process can exit without waiting for the cleanup callback.
However, this approach should only be used when skipping the callback during shutdown is acceptable.
If the cleanup operation must always finish, keep the timer referenced or perform the cleanup as part of an explicit shutdown sequence.
Using unref() With setInterval()
Repeated timers are another common reason for Node.js applications staying alive longer than expected.
For example, an application may use setInterval() to periodically collect metrics, refresh a local cache, or check the status of a non-critical service.
const metricsTimer = setInterval(() => {
console.log("Collecting application metrics");
}, 30000);
metricsTimer.unref();
console.log("Application is running");
The interval continues to execute while the process is active. However, it does not independently prevent the process from exiting.
This can be useful for background activities that should not control the application's lifetime.
Managing the Interval During Shutdown
Using unref() does not remove the need to manage timers properly. If an application has a defined shutdown process, it should still clear intervals when they are no longer needed.
const metricsTimer = setInterval(() => {
console.log("Collecting application metrics");
}, 30000);
metricsTimer.unref();
function stopMetricsCollection() {
clearInterval(metricsTimer);
console.log("Metrics collection stopped");
}
process.on("SIGTERM", stopMetricsCollection);
process.on("SIGINT", stopMetricsCollection);
This example demonstrates explicit timer cleanup when the process receives common termination signals.
In a production application, shutdown handling may also need to stop accepting new requests, finish important in-flight operations, close database connections, and release other resources. The interval cleanup should be part of that broader process.
Using ref() and unref() With setImmediate()
The same lifecycle controls are available for setImmediate().
Unlike setTimeout(), which schedules a callback after a specified delay, setImmediate() schedules a callback to execute after I/O events' callbacks in the event loop.
Consider this example:
const immediate = setImmediate(() => {
console.log("Immediate callback executed");
});
console.log(immediate.hasRef()); // true
immediate.unref();
console.log(immediate.hasRef()); // false
The Immediate object is referenced by default. Calling unref() changes its behavior so that it no longer keeps the event loop active.
If no other active resources remain, the process may exit before the callback executes.
This can be useful when scheduling optional work that does not need to extend the application's lifetime.
Comparing ref(), unref(), and hasRef()
Although these methods are related, each has a different responsibility.
| Method | Purpose | Effect on Event Loop |
|---|
| ref() | Makes an operation referenced | Keeps the process active while the operation remains active |
| unref() | Makes an operation unreferenced | Does not independently keep the process active |
| hasRef() | Checks the current reference state | Returns true or false without changing the state |
The methods are available on both Timeout and Immediate objects.
There is another important distinction between changing a timer's reference state and cancelling it.
| Operation | What It Does |
|---|
| unref() | Allows the process to exit without waiting for the timer |
| ref() | Requires the process to remain active while the timer is active |
| clearTimeout() | Cancels a timeout |
| clearInterval() | Cancels an interval |
| clearImmediate() | Cancels an immediate callback |
For example, calling unref() does not stop an interval from running while other application resources keep the process alive. To stop the interval itself, use clearInterval().
A Practical Example: Background Cache Refresh
Consider a Node.js API that maintains a local cache of frequently accessed configuration data.
The application refreshes the cache every minute. The API server itself keeps the process running while it handles incoming requests, so the cache refresh interval does not need to keep the process alive independently.
let configurationCache = {};
async function refreshConfiguration() {
try {
console.log("Refreshing configuration cache");
// Replace this with an actual API or database request.
configurationCache = {
updatedAt: new Date().toISOString(),
environment: process.env.NODE_ENV || "development"
};
console.log("Configuration cache updated");
} catch (error) {
console.error("Cache refresh failed:", error.message);
}
}
const cacheRefreshTimer = setInterval(() => {
refreshConfiguration();
}, 60000);
cacheRefreshTimer.unref();
console.log("Background cache refresh scheduled");
This example illustrates how unref() can be used for optional background work.
The API server can continue running normally because its server handle keeps the event loop active. If the server closes and no other referenced resources remain, the cache refresh interval will not force the process to stay alive.
In a real application, you should also consider the following:
- Load the initial cache before serving requests if the application depends on it.
- Handle failures without allowing an unhandled promise rejection.
- Prevent overlapping refresh operations if one refresh can take longer than the interval.
- Clear the interval during an explicit shutdown sequence.
- Use a dedicated background worker or scheduled job when the refresh must run independently of the API process.
An unreferenced timer is not a reliable job scheduler. It is only a way to control whether scheduled work keeps the current process alive.
Using ref() and unref() With Promise-Based Timers
Node.js also provides promise-based timer functions through the node:timers/promises module.
These functions allow developers to use timers with async and await instead of callback functions.
The promise-based timer APIs provide a ref option. Its default value is true, which means the timer keeps the event loop active. Setting it to false gives the timer unreferenced behavior.
For example:
const { setTimeout } = require("node:timers/promises");
async function runBackgroundTask() {
console.log("Starting background task");
await setTimeout(5000, undefined, {
ref: false
});
console.log("Background task completed");
}
runBackgroundTask();
The timer does not independently keep the process alive. If no other referenced resources remain, Node.js may exit before the promise resolves.
This option is useful when working with asynchronous code that relies on promise-based timers.
The same ref option is available for the promise-based setImmediate() and setInterval() APIs. For setInterval(), each iteration follows the configured reference behavior.
One important consideration is that using ref: false does not automatically cancel the promise or guarantee that the asynchronous operation will finish. It only changes the timer's effect on event loop liveness.
Best Practices for Using ref() and unref()
The following practices help avoid unexpected application shutdown behavior.
Use unref() Only for Optional Work
Before calling unref(), determine whether the scheduled operation can safely be skipped when the process exits.
Metrics collection, optional cache refreshes, and non-critical background checks may be suitable candidates.
Operations such as saving important transactions, writing required data, and completing essential application tasks should not depend on an unreferenced timer.
Keep Important Timers Referenced
Timers that represent work required for the application's normal operation should remain referenced.
Since Node.js timers are referenced by default, you generally do not need to call ref() unless you previously called unref().
Do Not Use unref() as a Replacement for Cleanup
An unreferenced interval can continue executing while other resources keep the process alive.
Always clear timers when their work is no longer needed. Use clearTimeout(), clearInterval(), or clearImmediate() depending on the type of scheduled operation.
Avoid Creating Too Many Unreferenced Timers
Calling unref() on a timer changes its lifecycle behavior; it does not remove the timer from memory or cancel its callback.
Creating large numbers of unnecessary timers can still add overhead. Prefer a shared scheduler or a smaller number of well-managed intervals when an application needs many background checks.
Make Shutdown Behavior Explicit
Production applications should have a clear shutdown strategy. Handle termination signals, stop accepting new work, finish essential operations, clear timers, and close external connections where appropriate.
Do not assume that an unreferenced timer will complete before the process exits.
Common Mistakes and Troubleshooting
Expecting an Unreferenced Timer to Always Execute
A common mistake is assuming that unref() simply reduces the priority of a timer.
It does not. If no other referenced resources remain, the process may exit before the callback runs.
The solution is to keep the timer referenced when its callback is essential.
Using unref() Instead of clearInterval()
Calling unref() on an interval does not stop repeated execution while the process remains active.
If the interval is no longer required, call clearInterval().
Assuming ref() Starts a Timer Again
The ref() method does not create a new timer or restart a completed operation. It only changes whether an active timer keeps the event loop alive.
Use setTimeout() or setInterval() to schedule new work.
Assuming Timer Delays Are Exact
A timeout delay is not a guarantee that the callback will execute at precisely the requested time. The event loop may be busy with other work, and Node.js does not guarantee exact callback timing.
Use appropriate scheduling mechanisms when an application requires accurate timing or dependable job execution.
Forgetting That Other Resources Can Keep the Process Alive
Calling unref() on one timer does not mean the entire application will exit.
An HTTP server, active socket, database connection, or another referenced timer may still keep the event loop running.
When troubleshooting a process that does not exit, inspect all active resources rather than focusing only on one timer.
Advantages and Limitations
Using ref() and unref() gives developers direct control over how scheduled operations affect process lifetime.
The main advantages include:
- Preventing optional background timers from unnecessarily extending application shutdown.
- Supporting cleaner lifecycle management in command-line tools and server applications.
- Allowing periodic monitoring tasks to run without independently keeping the process alive.
- Providing a simple way to restore normal timer behavior with ref().
- Supporting both callback-based and promise-based timer APIs.
However, these methods also have limitations:
- An unreferenced callback may never execute if the process exits.
- They do not cancel timers or release resources automatically.
- They do not guarantee exact timer execution times.
- They are not suitable replacements for durable background job processing.
- Developers must still manage application shutdown and important asynchronous operations explicitly.
Summary
Node.js provides ref(), unref(), and hasRef() to control whether scheduled timers and immediate callbacks keep the event loop active.
Timers created with setTimeout(), setInterval(), and setImmediate() are referenced by default. Calling unref() allows the process to exit without waiting for that particular operation, while ref() restores the normal behavior. The hasRef() method helps inspect the current state.
These methods are particularly useful for optional background work, periodic monitoring, cache refreshes, and command-line applications. However, they should not be used for tasks that must always complete.
The most important distinction is that unref() controls process lifetime, not timer execution or cancellation. Understanding this difference helps developers build Node.js applications with more predictable shutdown behavior and better resource management.
Join the conversation! Your thoughts help the community grow.