How to have timer stop when YouTube is ready?

You will notice that clicking on the play button too soon, and nothing happens. https://jsfiddle.net/jksoe8up/

How the code works is: As soon as a video has loaded, you can click on the cover / play button to start playing.

Here is a timer I added to the code.

I want to find out how many milliseconds it takes until YouTube is ready.

I want the timer to stop on its own when YouTube is ready.

How do I do that in the code?

Is there a way for me to do that in the code?

In my code there is a timer on the screen that starts on page load, what I want to happen is, for the timer to stop on its own when YouTube is ready.

// Interval
var interval;

// Counter
var enterDate = new Date();

function secondsSinceEnter() {
    return (new Date() - enterDate) / 1000;
}

// Event function
function evtFct() {
    var sec = secondsSinceEnter().toFixed(3);
    if (sec < 10)
        document.querySelector('button').innerText = sec + " seconds";
    else
        document.querySelector('button').innerText = 'You are here like for eternity';
}

// Add interval to keep the current time uptodate
interval = setInterval(evtFct, 0); // Call evtFct every tick

// Usage example
document.querySelector('button').onclick = function () {
    evtFct();
    clearInterval(interval); // Disable interval
}

Full Code

// Interval
var interval;

// Counter
var enterDate = new Date();
function secondsSinceEnter()
{
  return (new Date() - enterDate) / 1000;
}

// Event function
function evtFct()
{
  var sec = secondsSinceEnter().toFixed(3);
  if (sec < 10)
    document.querySelector('button').innerText = sec + " seconds";
  else
    document.querySelector('button').innerText = 'You are here like for eternity';
}

// Add interval to keep the current time uptodate
interval = setInterval(evtFct, 0); // Call evtFct every tick

// Usage example
document.querySelector('button').onclick = function()
{
  evtFct();
  clearInterval(interval); // Disable interval
}

const manageCover = (function makeManageCover() {
  const events = {};

  function show(el) {
    el.classList.remove("hide");
  }

  function hide(el) {
    el.classList.add("hide");
  }

  function openCurtain(cover) {
    hide(cover);
    const curtain = document.querySelector(".curtain");
    curtain.classList.add("slide");
    return curtain;
  }

  function showVideo(curtain) {
    const thewrap = curtain.parentElement.querySelector(".wrap");
    show(thewrap);
  }

  function coverClickHandler(evt) {
    const cover = evt.currentTarget;
    const curtain = openCurtain(cover);
    showVideo(curtain);
    cover.dispatchEvent(events.afterClickCover);
  }

  function init(callback) {
    const cover = document.querySelector(".play");
    cover.addEventListener("click", coverClickHandler);
    events.afterClickCover = new Event("afterClickCover");
    cover.addEventListener("afterClickCover", callback);
  }

  return {
    init
  };
}());

const videoPlayer = (function makeVideoPlayer() {
  const events = {};
  const eventHandlers = {};
  let player = null;


  function loadIframeScript() {
    const tag = document.createElement("script");
    tag.src = "https://www.youtube.com/iframe_api";
    const firstScriptTag = document.getElementsByTagName("script")[0];
    firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);
  }

  function onYouTubeIframeAPIReady() {
    const cover = document.querySelector(".play");
    const wrapper = cover.parentElement;
    const frameContainer = wrapper.querySelector(".video");
    videoPlayer.addPlayer(frameContainer);
  }

  function shufflePlaylist(player) {
    player.setShuffle(true);
    player.playVideoAt(0);
    player.stopVideo();
  }

  function onPlayerReady(event) {
    player = event.target;
    player.setVolume(100);
    shufflePlaylist(player);
    const iframe = player.h;
    iframe.dispatchEvent(events.afterPlayerReady);
  }

  function addPlayer(video) {

    const playlist = "0dgNc5S8cLI,mnfmQe8Mv1g,-Xgi_way56U,CHahce95B1g";

    const config = {
      height: 360,
      host: "https://www.youtube-nocookie.com",
      width: 640
    };
    config.playerVars = {
      autoplay: 0,
      cc_load_policy: 0,
      controls: 1,
      disablekb: 1,
      fs: 0,
      iv_load_policy: 3,
      loop: 1,
      playlist,
      rel: 0
    };
    config.events = {
      "onReady": onPlayerReady
    };

    player = new YT.Player(video, config);

    const iframe = player.h;
    const eventHandler = eventHandlers.afterPlayerReady;
    iframe.addEventListener("afterPlayerReady", eventHandler);
  }

  function play() {
    player.playVideo();
  }

  function addEvents(handlers) {
    eventHandlers.afterPlayerReady = handlers.afterPlayerReady;
    events.afterPlayerReady = new Event("afterPlayerReady");
  }

  function init(initEventHandlers) {
    addEvents(initEventHandlers);
    loadIframeScript();
    window.onYouTubeIframeAPIReady = onYouTubeIframeAPIReady;
  }

  return {
    addPlayer,
    init,
    play
  };
}());

videoPlayer.init({
  afterPlayerReady: function initCover() {
    manageCover.init(function playVideo() {
      videoPlayer.play();
    });
  }
});

   

I don’t know what you mean by “YouTube is ready”. Are you talking about when the player is ready, or when the video has loaded?

The API has events that gets fired (onReady for the player and onStateChange for the video). I would assume you can measure the time it takes for the events to fire and display the time/time delta. Or in your case, clear the interval when the event fires (inside the callback that gets fired by the API).


Are you just trying to measure the load performance of the videos, if so why and to what end? I’m sure it will depend on multiple factors and be different for different people (time of day, geolocation, CDN, user internet speed, etc.). Also, using setInterval/setTimeout isn’t as reliable compared to the Performance API (e.g. performance.now()).

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.