So I've made a simple custom progress bar for an audio object within my website. The progress bar works fine, but I've noticed it is very choppy. I also noticed that on websites such as Facebook and YouTube, their progress bar transitions seem to be exceptionally smooth (watch any video and you'll see what I mean).
I thought a workaround to this might be to use some crafty JavaScript and CSS, but in the end it just seemed very tacky, CPU heavy for no reason and looked essentially exactly the same as before. (This is what I came up with):
setInterval(function(){
var rect = elapsedContainer.getBoundingClientRect();
var percentage = audio.currentTime / audio.duration;
elapsed.style.width = (percentage * rect.width) + "px";
}, 33); // 30fps
.elapsed-container{
width: 100%;
height: 10px;
background: grey;
}
.elapsed{
left: 0;
height: 100%;
background: red;
transition: width 33ms linear;
}
JsFiddle
All help is appreciated, cheers.
You can try using window.requestAnimationFrame() instead of setTimeout(). The requestAnimationFrame callback allows the computer to try to get as close to 60fps as possible, but can alter the framerate for load, making it more performant than setTimeout(), which has to always match the specified framerate and can then end up skipping frames and then 'flicker' (see here for more info).
I also removed the CSS transition, so you are not mixing animations (since the requestAnimationFrame already animates at 60fps, the CSS transition is somewhat irrelevant)
// Change setTimeout to requestFrameAnimation
function progress_animation() {
var rect = container.getBoundingClientRect();
var percentage = audio.currentTime / audio.duration;
elapsed.style.width = (percentage * rect.width) + "px";
window.requestAnimationFrame(progress_animation);
};
// Only run animation when relevant
document.getElementById("play").onclick = function(){
window.requestAnimationFrame(progress_animation);
audio.play();
}
https://jsfiddle.net/4ymch2jg/
This appears smoother for me at least
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With