YouTube API - Getting current time in a global variable

3.5k views Asked by At

Here in this jsfiddle http://jsfiddle.net/StephanieQ/oo1g1762/

  // This code loads the IFrame Player API code asynchronously.
  var tag = document.createElement("script");
  tag.src = "//www.youtube.com/iframe_api";
  var firstScriptTag = document.getElementsByTagName("script")[0];
  firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);

  // This function creates an <iframe> (and YouTube player)
  // after the API code downloads.
  var player;
  window.onYouTubeIframeAPIReady = function() {
    player = new YT.Player("player", {
      "height": "315",
      "width": "560",
      "videoId": "bHQqvYy5KYo",
      "events": {
        "onReady": onPlayerReady,
        "onStateChange": onPlayerStateChange
      }
    });
  }

      // 4. The API will call this function when the video player is ready.
      function onPlayerReady(event) {
        event.target.playVideo();
      }
       function onPlayerStateChange(event){
        var time;
        time = player.getCurrentTime();
        $("#timeHolder").text(time);

       }

I'm using youTube's player object method player.getCurrentTime(); to find out the time on an embedded youTube video. As you can see, every time the player state is changed, "time" is redefined and inserted in the timeHolder div. Is there any way to have "time" be continuously defined so it matches the current time and inserted in the div as it updates? (not triggered by player state change?)

More importantly, I'm playing around with this because I'd like to be able to use the current time on the youTube video to interact with other external scripts, how can I make it global?

1

There are 1 answers

0
North On BEST ANSWER

Use setInterval() to repeat the function. When even.data equals to 1 means youtube is playing, so let the function repeat. Otherwise is not playing, then use clearInterval() to stop the repeat function.

var myTimer; 
function onPlayerStateChange(event){
    if(event.data==1) { // playing
        myTimer = setInterval(function(){ 
            var time;
            time = player.getCurrentTime();
            $("#timeHolder").text(time);
        }, 100); // 100 means repeat in 100 ms
    }
    else { // not playing
        clearInterval(myTimer);
    }
}

See jsfiddle here