I have a 4 videos and preloader, that should hide when all the videos is fully buffeder
<div id="preload">
<h1>
Download...
</h1>
</div>
<video preload="auto" class="active">
<source src="video1.mp4" type='video/mp4;'>
</video>
<video preload="auto">
<source src="video2.mp4" type='video/mp4;'>
</video>
<video preload="auto">
<source src="video3.mp4" type='video/mp4;'>
</video>
<video preload="auto">
<source src="video4.mp4" type='video/mp4;'>
</video>
There is the code that checks if videos is buffered
preload = [];
preloadOverlay = document.querySelector('#preload');
videos = document.querySelectorAll("video")
[...videos].forEach(function(video, index) {
video.addEventListener('canplay', function(){
let timerId = setTimeout(function tick() {
// console.log(preload)
// console.log(video.buffered.end(0), video.duration)
if(preload.length < 4)
{
if(video.buffered.end(0) === video.duration)
{
preload.push(index)
}
timerId = setTimeout(tick, 200);
}
else if(preload.length === 4)
{
clearTimeout(timerId);
preloadOverlay.classList.add('hide');
}
}, 200);
})
})
but sometimes buffering just stops, for example all the videos are 3 seconds long, but buffering stops at 2 second
i changed my code a little bit to
[...videos].forEach(function(video, index) {
video.addEventListener("canplaythrough", function() {
preload.push(index)
});
let timerId = setTimeout(function tick() {
if(preload.length < 4)
{
console.log(preload)
console.log(video.buffered.end(0), video.duration)
timerId = setTimeout(tick, 200);
}
else if(preload.length === 4)
{
clearTimeout(timerId)
preloadOverlay.classList.add('hide')
layoutAnimation(timeoutClassRemover)
}
}, 200);
})
but still, one or two videos does not load till the end, and stops randomly
I wouldn't use the timer for this task. Promises look more suitable here from my perspective.
Also, I would recommend removing
;at the end of typesvideo/mp4.Please let me know if this helps.