HTML5 video autoplay but with a 5 seconds of delay

Billy picture Billy · Jan 2, 2014 · Viewed 51.7k times · Source

I have a 20 second long HTML5 video loop as the background on my webpage and it is set to autostart. Is it possible to delay the video autoplay for 5 seconds? I am trying to allow the video to load completely before trying to play to prevent it from stuttering as much. Here is my current code:

<video id="video_background" poster="images/dmm_background.jpg" controls="controls" preload="true" autoplay="true" loop="loop" muted="muted" volume="0"> 
<source src="videos/backgroundvideo.mp4" type="video/mp4"> 
<source src="videos/backgroundvideo.webm" type="video/webm">
</video>
</video>

Any help is greatly appreciated!!

Answer

Joe Johnston picture Joe Johnston · Sep 19, 2015

This is a working solution for me. You should use canplay as a best practice to be sure the browser can play the video. Also, here is a straight javascript solution.

Note: I removed autoplay, an extra closing video tag, and formatted your muted & loop flags.

var video = document.getElementById("video_background");
video.addEventListener("canplay", function() {
  setTimeout(function() {
    video.play();
  }, 5000);
});
<video id="video_background" poster="images/dmm_background.jpg" controls="controls" preload="true" muted loop>
  <source src="https://d2v9y0dukr6mq2.cloudfront.net/video/preview/SsRadVyPGjdkeg9tt/videoblocks-computer-hacking-in-process-cyber-security-concept_h-l3zbu4xb__PM.mp4">
    <source src="videos/backgroundvideo.webm" type="video/webm">
</video>