Reputation: 5197
Every second it goes after started playing the video, I want it to run the function which is called showComments
To make sure it's running every second, I just added
alert(getCurrentTime().toFixed());
However, it's not even running :(
How can I make this run showComments function every second?
Here's the demo and codes.
demo: https://jsfiddle.net/f0buajyz/
<div id="player"></div>
<script>
var tag = document.createElement('script');
tag.src = "https://www.youtube.com/iframe_api";
var firstScriptTag = document.getElementsByTagName('script')[0];
firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);
var player;
function onYouTubeIframeAPIReady() {
player = new YT.Player('player', {
height: '270',
width: '480',
videoId: 'mzIdhSTHJts',
});
}
var fixedTimeHtml5Youtube = 0;
function getStatus(){
if(player.getCurrentTime().toFixed() != fixedTimeHtml5Youtube){
alert(getCurrentTime().toFixed());
showComments(player.getCurrentTime().toFixed());
fixedTimeHtml5Youtube = player.getCurrentTime().toFixed();
}
}
</script>
Upvotes: 1
Views: 1342
Reputation: 3712
You can use setInterval to run the function every 1000ms(1s), in combination with the onStateChange
event.
Whenever the event fires, it checks if the video is playing. If its playing, it starts calling the showComments
function every second. Otherwise it stops the interval.
Working fiddle: https://jsfiddle.net/crisbeto/f0buajyz/4/
HTML:
<div id="player"></div>
<textarea id="output"></textarea>
JavaScript:
var tag = document.createElement('script');
var player = null;
var interval = null;
tag.src = "https://www.youtube.com/iframe_api";
document.body.appendChild(tag);
window.onYouTubeIframeAPIReady = function(){
player = new window.YT.Player(document.getElementById('player'), {
height: '270',
width: '480',
videoId: 'mzIdhSTHJts',
events: {
onStateChange: function(event){
callback(event);
}
}
});
}
function callback(event){
var playerStatus = event.data;
// player is playing
if(playerStatus === 1){
interval = setInterval(showComments, 1000);
// player is stopped
}else if(interval){
clearInterval(interval);
}
}
function showComments(){
document.getElementById('output').value += "\n showComments called.";
}
Upvotes: 3