Search code examples
node.jstimeoutsettimeoutlifecycle

Node.JS: setTimeout that does not keep the process running


I would like to add a one hour timeout to this process so that it will not stay forever in the case of a stream deadlock. The only problem is if I say setTimeout, the process has no opportunity to end ahead of schedule.

Is there a way to put in a forced exit timeout after about an hour, without keeping the process running? Or am I stuck between using process.exit and doing without this timeout?


Solution

  • I don't know when unref was added to Node but this is now one possible solution. Reusing Matt's code:

    var timeoutId = setTimeout(callback, 3600000);
    timeoutId.unref(); // Now, Node won't wait for this timeout to complete if it needs to exit earlier.
    

    The doc says:

    In the case of setTimeout when you unref you create a separate timer that will wakeup the event loop, creating too many of these may adversely effect event loop performance -- use wisely.

    Don't go hog wild with it.