I have a countdown timer, in the style of a bar, that slowly decreases in width.
Check the following code:
HTML
<div id="timer"><span></span></div>
CSS
#timer {
height: 30px;
display: block;
overflow: hidden;
background: grey;
}
#timer span {
width: 100%;
height: 100%;
display: block;
background: green;
-webkit-animation-name: decreasewidth;
animation-name: decreasewidth;
-webkit-animation-iteration-count: 1;
animation-iteration-count: 1;
-webkit-animation-timing-function: linear;
animation-timing-function: linear;
-webkit-animation-fill-mode: forwards;
animation-fill-mode: forwards;
-webkit-animation-duration: 20000ms;
animation-duration: 20000ms;
}
@keyframes decreasewidth {
to { width: 0% }
}
@-webkit-keyframes decreasewidth {
to { width: 0% }
}
Sadly, the animation will halt when the page isn't in use, eg. browsing another tab or window. I understand this is ordinary among browsers and helps save processing power.
Problem is, I want my timer to be accurate. That means holding true to its position even when the user flicks to other tabs during. How would I go about achieving this?
At first, my thoughts were along the lines of calculating the amount of ms the user was absent from the page and then updating the timer's span accordingly on return. But this would only happen on the focus
event, which relies on user activity.
I also tried a good ol' javascript setInterval
technique which simply updated the width of the span every second. Not only did this look terrible - the same problem occurred. Most browsers increase the interval time when inactive.
Interested to hear some ideas on how to handle this.
TL;DR
I need an animated countdown timer bar, that keeps true to its position even when the page is inactive.
EDIT
I know this is noticeable in Safari.