Search code examples
javascriptcountdowncountdowntimer

Basic Javascript Countdown Timer Taking Longer Than Time Set


I'm trying to code a VERY SIMPLE countdown timer. At first, it seemed to be done and working fine. I was excited. But then, upon testing it out, I realized that a 30-min countdown seemed to take for ever. So I looked into it and found that what my timer was timing as 30 mins was, in the real world, almost 50 mins!

I've tried debugging the thing and can't find where it's going wrong. At first I thought maybe the setInterval was responsible and not working at exactly one second intervals. But I can't see anyone else has had that issue. Supposedly it should always work. And, when checking it closely, by making the function print put ...getSecond() data it does seem like it's working perfectly. However, time is being added on at some point!

I've tried this approach. Getting the info from the new Date() function and then subtracting the starting timestamp with the the finishing timestamp... etc., etc. The thing is this was supposed to be a 5-10 min code work and, thus, complicating it in this way defeats the purpose!

So I'm coming to you guys for help! I've quickly set it up in this jsFiddle for you guys to try out and hopefully someone out there will see where the glitch is.

The timer basically just shows the minutes going down, as I don't want it to count seconds (seconds going by, I find, frustrate people who have to fulfill a task in a specific time). I've unhidden the seconds so you guys can see them, though. And it should print out the time it starts and time it ends, so you can see the difference between the time your setting up for the countdown and the actual time it takes for the countdown to end. If one tries out the 1-min countdown, for example, one should find one or two seconds are added. If one tries out the 30-mins countdown one should find about 50 mins are added.


Solution

  • At first I thought maybe the setInterval was responsible and not working at exactly one second intervals

    Yes, you cannot expect it to fire exactly every second as timer is based on local system clock cycle. For example: if on a system, 33 miliseconds = 1 clock cycle => 1000 seconds is almost 30.3 clock cycles, but the system has to round up the value and fire the event every 31 clock cycles. That's how the time adds up.

    As javascript is single-threaded, there is another overhead involved to execute your timer callback