Hozefa Hozefa - 4 months ago 12
jQuery Question

HTML5 - Fire event every few seconds while video is playing

I want to track user engagement for a video, by tracking how many users are dropping of at different time interval.

For this I need to fire a tracking event, every 15 seconds while the video is playing.

The

playing
event is triggered once. I need something which I can use throughout the life of the video.

var _video = $('video')[0],
timeoutID;
$(_video).on('playing', function(event){
timeoutID = window.setTimeout(function() {
console.log("video is playing");
}, 15000);
}).on('ended', function(event){
console.log("video eneded");
window.clearTimeout(timeoutID);
});

Answer

use window.setInterval instead of window.setTimeout

$(_video).on('playing', function(event){
        timeoutID = window.setInterval(function() {
            console.log("video is playing");
        }, 15000);
    }).on('ended', function(event){
        console.log("video eneded");
        window.clearInterval(timeoutID);
    });
Comments