Triggering a simple event with YouTube iframe API / sync event with player.getCurrentTime

398 Views Asked by At

This seems like a relatively easy thing, but the lack of examples on the web (and the deprecation of the JS API) has my head spinning, so here goes. I want some code to execute when a YouTube video gets to a certain time. You can see examples of this here and here.

What I'm trying to do is far less complicated. When the video is 3 seconds in, I want to put some text on the page. That's it.
http://jsfiddle.net/StephanieQ/2sj9smnd/

 var youtubetime;
function onPlayerStateChange(event){
    if(event.data==1) { // playing
        myTimer = setInterval(function(){ 
            youtubetime = Math.round(player.getCurrentTime()*10)/10;
            $("#timeHolder").text(youtubetime);
            //return youtubetime;
        }, 100);
    }
    else { // not playing
        clearInterval(myTimer);
    }
}

if( youtubetime > 3  ) {
     $("#results").text("Working!");

But it doesn't work. I've tried parseFloat (which shouldn't be needed because player.getCurrentTime(); should return a number.) and that doesn't help. I have the current time to one decimal point displayed in a div on the bottom so clearly the variable I'm using is defined and working.

Why doesn't this work? It seems so simple...

Notes: iframe API only since the YouTube's JS API is deprecated.

EDIT: setInterval holds the key to my salvation!

setInterval(function () {
if (youtubetime > 3) { $("#results").text("Works!"); } }, 100);

I'm an idiot...

1

There are 1 best solutions below

0
On BEST ANSWER

Per not_a_bot's suggestion, I'm going to add my edit to answer my own question since I solved it myself and maybe others can learn from this.

I'm using setInterval to check every tenth of a second (100ms) if the variable youtubetime is greater than three seconds. Without this periodic check the anonymous function does not work (otherwise the variable is only checked on page load.)

setInterval(function () {
if (youtubetime > 3) { $("#results").text("Works!"); } }, 100);

'Cause knowledge is power!