Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How long can NodeJS `setTimeout` wait?

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?

like image 787
McKabue Avatar asked Sep 15 '25 09:09

McKabue


2 Answers

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 delay will set to 1. (ref)

Answering your use-case

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

like image 86
Laxmikant Dange Avatar answered Sep 17 '25 00:09

Laxmikant Dange


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

like image 35
squgeim Avatar answered Sep 16 '25 22:09

squgeim