How long can NodeJS `setTimeout` wait?

Viewed 602

Can NodeJS setTimeout delay excecution of function for a week? (assuming the server doesnt go down...) In some other servers like ASP.NET CORE, the server will sleep when not in use, hence we can't use such.

Does the same happen in the NodeJS world, or the server remains on forever?

2 Answers

There is nothing in the documentation that would suggest it would not work. However, if the length in millisecond is greater than 2147483647 (24 day 20 h 31 min 24 s), the delay is set to 1.

https://nodejs.org/api/timers.html#timers_settimeout_callback_delay_args

The behavior is different on a browser. Unsurprisingly, the timeout is delayed if the associated tab is inactive.

If the method context is a Window object, wait until the Document associated with the method context has been fully active for a further timeout milliseconds (not necessarily consecutively).

Otherwise, if the method context is a WorkerUtils object, wait until timeout milliseconds have passed with the worker not suspended (not necessarily consecutively).

https://www.w3.org/TR/2011/WD-html5-20110525/timers.html#dom-windowtimers-settimeout

Answering your question

setTimeout has the second argument of delay as a 32-bit signed integer. So the value can not be greater than 2147483647 (about 24.8 days). When the delay is larger than 2147483647, then the day will set to 1. (ref)

Answering your use-case

instead of using setTimeout for such a long delay, you can run cron job.

Related