Reputation: 63
I'm trying to trigger function(s) when player.getCurrentTime() == 10
sec (and many more intervals like this).
I can do this with JS timing events but it's not accurate and slows my browser very much..
Is there an alternate?
Current code:
trigFuncAt = Array(3, 5, 7, 10);
setInterval(checkFunc(), 200);
function checkFunc(){
if( include( trigFuncAt, player.getCurrentTime() ) ){
DoThis();
}
}
function include(arr,obj) {
return (arr.indexOf(obj) != -1);
}
function DoThis(){...}
player.getCurrentTime()
is a timer kind of variable it changes for every ms.
YT API: https://developers.google.com/youtube/iframe_api_reference
Upvotes: 0
Views: 1483
Reputation: 5997
The idea is that you use setTimeout instead of setInterval, since you cannot guarantee that the time the function needs to execute is enough between interval time. Also you need to cast to int the current time. Sample code:
// implicit global video containing YT video
var keypoints = [1, 2, 3, 10, 15];
var updatePlayerInfo = function() {
var played,
i = 0,
keypoint;
// not ready?
if (!video.getCurrentTime) {
return false;
}
// ready!
if (played = parseInt(video.getCurrentTime(), 10)) {
for (; keypoint = keypoints[i++]; ) {
if (keypoint === played) {
// do something
doSomething();
break;
}
}
}
// throttle function!
setTimeout(function(){
updatePlayerInfo();
}, 250);
};
Upvotes: 1