Categories
JavaScript Answers

How to Prevent “The play() request was interrupted by a call to pause()” Error with Video Elements?

Spread the love

To fix the “The play() request was interrupted by a call to pause()” error, we can check if the video is played or paused we can check if the video is paused before playing, and check if the video is playing before pausing it.

To do this, we write the following HTML:

<video width="400">
  <source src="http://commondatastorage.googleapis.com/gtv-videos-bucket/sample/BigBuckBunny.mp4" type="video/mp4">
  Your browser does not support HTML video.
</video>
<button id='play'>
  play
</button>
<button id='pause'>
  pause
</button>

Then we write:

const video = document.querySelector('video')
const play = document.querySelector('#play')
const pause = document.querySelector('#pause')
let isPlaying = false;

video.onplaying = () => {
  isPlaying = true;
};

video.onpause = () => {
  isPlaying = false;
};

const playVid = () => {
  if (video.paused && !isPlaying) {
    video.play();
  }
}

const pauseVid = () => {
  if (!video.paused && isPlaying) {
    video.pause();
  }
}

play.addEventListener('click', playVid)
pause.addEventListener('click', pauseVid)

We get the video and button elements with document.querySelector .

Then we define the isPlaying variable which indicates whether the video is playing or not.

Then we set isPlaying to true when the video is playing in the onPlaying method.

And we set isPlaying to false when the video is playing in the onPlayingmethod.

Then we have the playVid function that checks if the video is paused with video.paused and isPlaying .

And if video.paused is true and isPlaying is false , we call video.play to play the video.

And if video.paused is false and isPlaying is true, we call video.pause to pause the video in the pauseVid function.

Finally, we call addEventListener on play and pause to add the functions as click event listener functions.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *