DEV Community

Discussion on: Handling time intervals in JavaScript

Collapse
 
curtisautery profile image
Curtis Autery

I wouldn't use the seconds timer inside of your setInterval loop like that. The setInterval function attempts to fire on time, but doesn't if load if heavy. Running some quick tests with calculating primes while using your method for a counter, the true time and the counter's assumption about how much time had fast strayed quite a bit.

Instead of decrementing a timer once per interval, why don't you store the current date as a variable when the timer is instantiated? You can do the rest with creating new date objects and subtracting them from the start time to get elapsed milliseconds.

Collapse
 
amit_merchant profile image
Amit Merchant

Hey @curtis , This seems really good approach. I'll definitely try it in my app. Thanks!