themike
themike

Reputation: 149

Youtube API - call a function at certain time in the video

I'm using default YouTube API example, is it possible to call a function at or after a certain time in the video?

Like "if video >= 20 seconds, call function"

I am currently using a settimeout to call this function, but it would be more precise to run it off the video timer, if possible.

Upvotes: 1

Views: 905

Answers (2)

Jonathan
Jonathan

Reputation: 9151

Since no one actually posted the "loop" that is very much required to make this work:

function checkTime() {
    if (player.getCurrentTime() >= 20) {
        console.log("Played 20 sec");
    } 
    else 
        window.setTimeout(checkTime, 100);
}

window.setTimeout(checkTime, 100);

jsFiddle demo

Upvotes: 3

Dean
Dean

Reputation: 1542

You can make something like :

var player = document.getElementById("my_player");
var flag = 0;

if (!flag && player.getCurrentTime() >= 20) {
  flag = 1;
  doSomethingOnce();
}

The flag make sure it only append once.

Use this in a loop to catch the right moment.

Upvotes: 3

Related Questions