x32x01
ADMINISTRATOR
- by x32x01 ||
Why the iPhone Timer App displays a Fake Time
While building my event timer app called stagetimer.io I came across a peculiarity with displaying time and found out that the iPhone timer addresses it by showing us a fake time. By definition, a countdown shows how much time is left. So if the countdown says 5s we assume there are 5 seconds left. But that’s not the whole truth.TL;DR
The iPhone countdown timer doesn’t strictly display the correct time but adds 500ms, or half a second, to the remaining time. It does this to make the reading of time more intuitive for humans. The alarm at the end of the countdown is not affected by this 500ms inaccuracy.
Countdowns are tricky
Javascript likes to use milliseconds when dealing with time, 1000ms equals 1s. Here is an example of a 5s countdown that starts at 5000ms and uses the setInterval() function to deduct 10ms every 10ms, simple enough. Milliseconds are converted to seconds by dividing by 1000 and rounding down like so: Math.floor(milliseconds / 1000)
Checking how the iPhone does it
Now I was curious how my iPhone solves this conundrum. So I set my iPhone timer to 5s:
I figured that the good folks at Apple add an extra fake 500ms to the actual time to start that countdown display at 5s instead of 4s. The timer ends and the phone beeps if the actual time hits 0s and the “fake” time hits 500ms. So they faced the same problem I did and came up with a practical solution. After all, if you start a 5s countdown, it should start at 5s right? For illustration, here is my simple timer doing the same trick.
Edit: About rounding time
Some have pointed out that the problem could be solved more easily by rounding to the nearest second or rounding up instead of rounding down. This is correct. Suppose we have 5459543ms that we want to bring into the traditional form HH:mm:ss.
I first divided the number into hours, minutes, and seconds with the help of some modular arithmetic and applied the rounding afterward. Rounding down results in 01:30:59, which is correct, but rounding to the nearest integer or rounding up results in the impossible time 02:31:60.
C:
time = 5459543
seconds = (time / 1000) % 60 // 1.517
minutes = (time / 60000) % 60 // 30.992
hours = (time / 3600000) % 24 // 59.543
C:
time = 5460000
seconds = (time / 1000) % 60 // 0.000
minutes = (time / 60000) % 60 // 31.000
hours = (time / 3600000) % 24 // 1.517