Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to retry loading video again once it fails

In my page i am showing a Video loaded from Sprout this way

In case , if something went wrong , means video is not loaded due to 404 , or 403 http status , how can i retry for 4 times ? (waiting for 5 seconds each time )

This is my code

<video id="video" width="200" height="200" controls>
   <source id='currentVID' src="" type="video/mp4">
</video>


var actualvideo = 'https://api-files.sproutvideo.com/file/7c9adbb51915e2cdf4/b6e4822661adad1aremovethis/240.mp4';
if (actualvideo !== '') {
    var video = document.getElementById('video');

    $('video source').last().on('error', function() {

    alert('something went wrong');

    });


    video.pause();
    var source = document.getElementById('currentVID');
    source.setAttribute('src', actualvideo);
    video.appendChild(source);
}

https://jsfiddle.net/o2gxgz9r/9974/

like image 517
Pawan Avatar asked Jul 12 '17 11:07

Pawan


2 Answers

Have a look at this:

var retry = 0;
$('video source').on('error', function() {
    if(retry < 4){
      retry++;
      alert('something went wrong! Retrying.. '+retry+'');
      $n = $(this);
        setTimeout(function(){
        $n.appendTo( $('#video') );
      },5000);
    }
});

The code appends video's source again to the video tag up to 4 times with 5 sec delay.

Working fiddle:
https://jsfiddle.net/3uto3swj/

like image 104
Ezenhis Avatar answered Oct 15 '22 01:10

Ezenhis


This is a simple case of using setTimeout() to stall and try again.

// set counter before defining listener 
// we'll do 4 retries (or 5 total attempts)
let retries = 4;

source.addEventListener('error', function onErr(){
    // test for truthiness, then decrease by 1
    if (retries--) { 

    // after 5000ms re-append source
    setTimeout( function retry(){ 
        video.appendChild( source );
    }, 5000);
  }
});

I tweaked your fiddle to put it in action. I removed the little sprinkle of jQuery, since you don't seem to really be using it anyway. Looks like you just didn't know how to listen for an event with vanilla JS. Plus I added a pretend network recovery and a cat. ;D

😸 fiddle

Sorry if I missed any semicolons. I normally don't use them.

like image 28
skylize Avatar answered Oct 15 '22 00:10

skylize