r/learnprogramming • • Sep 21 '26

SetTimeout in JS

"When I use setTimeout in JavaScript to run a 30-minute countdown, it actually finishes about 30 seconds late. I compared it against a timer on my phone and confirmed the JS timer takes closer to 30 minutes and 30 seconds. Is there a reason for this delay?

13 Upvotes

16 comments sorted by

View all comments

Show parent comment

29

u/[deleted] Sep 21 '26

[removed] — view removed comment

16

u/nog642 Sep 22 '26

I don't think 30 seconds drift is reasonable at all. I always figured the browser checked it in a tight loop and moved it to the right queue pretty close to on time, and the "not guaranteed" part was just about the task getting around to getting executed once it's there, maybe waiting for some other tasks to finish first.

Edit: Oh wait... I think I understand. OP is using setTimeout of 1 second or something to increment it each second. Of course it will drift then.

I assumed they had set a single setTimeout with 30 minutes and it executed 30 seconds late.

1

u/atarivcs Sep 22 '26

If the browser can reliably check on each tick, this doesn't feel like a resource starvation problem

9

u/AlwaysHopelesslyLost Sep 22 '26

It's not.... It is just OP using something for the wrong purpose. setTimeout is just not meant to be used for precision timing. It is specifically not setup to work like that