Play the embed YouTube video at given start and end timestamp

Attempt to answer this question: https://stackoverflow.com/q/77938623/4092887

by MauricioSOes

HTML

<div id="player"></div>

JavaScript

var tag = document.createElement('script');

tag.src = "https://www.youtube.com/iframe_api";
var firstScriptTag = document.getElementsByTagName('script')[0];
firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);

var player;

function onYouTubeIframeAPIReady() {
  player = new YT.Player('player', {
    videoId: 'iuig147bQnY',
    height: '390',
    width: '640',
    playerVars: {
      mute: 1, // Optional (if you want to autoplay the video)
      autoplay: 1,
      start: 0,
      end: 6,
      controls: 0,
      fs: 0,
      playsinline: 1,
      modestbranding: 1,
      rel: 0,
      loop: 1,
      enablejsapi: 1,
    },
    events: {
      'onReady': onPlayerReady,
      'onStateChange': onPlayerStateChange
    }
  });
}

function onPlayerReady(event) {
  event.target.playVideo();
}

function onPlayerStateChange(event) {
  // When the video ends, it will play again.
  // See: https://developers.google.com/youtube/iframe_api_reference?hl=en#Events

  // Using ths way of loop the video it will not show related videos, but 
  // it will show loading a little bet the video.
  if (event.data == YT.PlayerState.ENDED) {
    player.seekTo(0);
  }
}