skip to Main Content

I am learning development and have an uncaught load error on a video I have as a background of a website.

The goal is to have it automatically choose between two different videos on webpage load, but I seem to be missing something in the code below, as I am getting error: : Uncaught (in promise) DOMException: The play() request was interrupted by a new load request.

Can anyone help me to understand the error at hand, and how I can fix it?

HTML:

  <video class="my-video" id="myVideo" autoplay loop muted preload="none" playsinline>
    <source src="videolink1.mp4" type="video/mp4">
    Your browser does not support the video tag.
  </video>

JAVASCRIPT:

const video = document.getElementById("myVideo");

const videoSources = [
  'https://videolink1.mp4',
  'https://videolink2.mp4'
];

function changeVideoSourceRandomly() {
  const randomIndex = Math.floor(Math.random() * videoSources.length);
  const randomSource = videoSources[randomIndex];
  const source = video.querySelector('source');
  source.src = randomSource;
  video.load();
}

changeVideoSourceRandomly();

I havent been understanding the google error result, could use some help understanding how to adjust my code.

2

Answers


  1. Chosen as BEST ANSWER

    This fixed my problems!

    function changeVideoSourceRandomly() {
      const randomIndex = Math.floor(Math.random() * videoSources.length);
      const randomSource = videoSources[randomIndex];
      const source = video.querySelector('source');
      source.src = randomSource;
      video.load();
    }
    
    // var playPromise = video.play();
    video.play().then(_ => {
        changeVideoSourceRandomly();
      })
      .catch(error => {
      console.log("Video not loaded", error)});
    

  2. you have to pause the video before changing to a new video.

    change your code to this and it should work.

          function changeVideoSourceRandomly() {
      const randomIndex = Math.floor(Math.random() * videoSources.length);
      const randomSource = videoSources[randomIndex];
      const source = video.querySelector('source');
      
       
      video.pause(); 
      source.src = randomSource; 
      video.load();
       
      if (!video.paused) {
        video.play();
      }
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search