1
votes

I want to delay the autoplay of a youtube video. My video currently autoplays as soon as the page loads. Here is the iframe code I am using:

iframe allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture" allowfullscreen="" frameborder="0" height="315" src="#videolink#?autoplay=1&controls=0" title="YouTube video player" width="560"></iframe

However, there always seems to be a slight delay of start time due to video loading when the page loads. To control for the start time point of the video, I am trying to figure out a way to delay the start of autoplay by 5 seconds. I read posts on using timeout function in javascript, but not exactly sure of the lines to put in there.

Any help would be appreciated.

1

1 Answers

1
votes

You do not need to place an iframe now, the following code will autoplay the video after 5 seconds. Stack Overflow is not playing the video, you can save it and try it manually.

<div id="ytplayer"></div>
<script>
  var tag = document.createElement('script');
  tag.src = "https://www.youtube.com/player_api";
  var firstScriptTag = document.getElementsByTagName('script')[0];
  firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);
  var player;
  function onYouTubePlayerAPIReady() {
    player = new YT.Player('ytplayer', {
      height: '360',
      width: '640',
      videoId: '668nUCeBHyY' //Place the video id here
    });
  }
  setTimeout(function() {
        player.playVideo();
    }, 5000);
      var tag = document.createElement('script');
      tag.src = "https://www.youtube.com/player_api";
      var firstScriptTag = document.getElementsByTagName('script')[0];
      firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);

</script>