Skip to content

Instantly share code, notes, and snippets.

@rihardn
Last active May 24, 2023 05:50
Show Gist options
  • Save rihardn/9525c7fdf03b22db1396299601d2e3c3 to your computer and use it in GitHub Desktop.
Save rihardn/9525c7fdf03b22db1396299601d2e3c3 to your computer and use it in GitHub Desktop.
Play and Pause HTMl video with promises

How to play and pause HTML video with promises

const video = document.getElementById('myVideo');
const playBtn = document.getElementById('playBtn');
const pauseBtn = document.getElementById('pauseBtn');

function playVideo() {
  return new Promise((resolve, reject) => {
    if (video.paused) {
      video.play();
      video.onplaying = resolve;
      video.onerror = reject;
    } else {
      resolve(); // Resolve immediately if the video is already playing
    }
  });
}

function pauseVideo() {
  return new Promise((resolve, reject) => {
    if (!video.paused) {
      video.pause();
      video.onpause = resolve;
      video.onerror = reject;
    } else {
      resolve(); // Resolve immediately if the video is already paused
    }
  });
}

playBtn.addEventListener('click', () => {
  playVideo()
    .then(() => {
      console.log('Video started playing.');
    })
    .catch((error) => {
      console.error('An error occurred while playing the video:', error);
    });
});

pauseBtn.addEventListener('click', () => {
  pauseVideo()
    .then(() => {
      console.log('Video paused.');
    })
    .catch((error) => {
      console.error('An error occurred while pausing the video:', error);
    });
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment