How to prevent "The play() request was interrupted by a call to pause()" error?

Owen M picture Owen M · Apr 22, 2016 · Viewed 149.9k times · Source

I made a website where if the user clicks, it plays a sound. To prevent the sound from overlapping, I had to add the code:

n.pause();
n.currentTime = 0;
n.play();

But that causes the error: The play() request was interrupted by a call to pause()
To come up each time the sound event is triggered right after another trigger. The sounds still plays fine, but I want to prevent this error message constantly popping up. Any ideas?

Answer

User 1058612 picture User 1058612 · Apr 27, 2016

I have encountered this issue recently as well - this could be a race condition between play() and pause(). It looks like there is a reference to this issue, or something related here.

As @Patrick points out, pause does not return a promise (or anything), so the above solution won't work. While MDN does not have docs on pause(), in the WC3 draft for Media Elements, it says:

media.pause()

Sets the paused attribute to true, loading the media resource if necessary.

So one might also check the paused attribute in their timeout callback.

Based on this great SO answer, here's a way you can check if the video is (or isn't) truly playing, so you can safely trigger a play() without the error.

var isPlaying = video.currentTime > 0 && !video.paused && !video.ended 
    && video.readyState > 2;

if (!isPlaying) {
  video.play();
}

Otherwise, @Patrick's answer should work.