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);
});
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);
});
You can use the timeupdate
event instead, it updates whenever the video's currentTime
changes, or in other words it updates as the video is playing and gives you the amount of video the user has actually seen
var _video = $('video')[0];
$(_video).on('timeupdate', function() {
var hasPlayedTime = _video.currentTime;
});
var _video = $('video')[0];
$(_video).on('timeupdate', function(event){
var hasPlayedTime = _video.currentTime;
$('#result').html('<strong>Elapsed : </strong>' + hasPlayedTime);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<video controls="" style="width:240px;height:180px;">
<source src="http://www.html5rocks.com/en/tutorials/video/basics/devstories.webm" type="video/webm;codecs="vp8, vorbis"" />
<source src="http://www.html5rocks.com/en/tutorials/video/basics/devstories.mp4" type="video/mp4;codecs="avc1.42E01E, mp4a.40.2"" />
</video>
<span id="result" style="position:relative; top: -100px; left: 20px"></span>
To act only every fifteen seconds on an event such as that, we need to add some math and logic
var _video = $('video')[0],
debounce = true,
seconds = 5; // set to 15 instead
$(_video).on('timeupdate', function(event){
var hasPlayedTime = _video.currentTime;
var intPlayedTime = parseInt(hasPlayedTime, 10);
var isFifteen = intPlayedTime % seconds === 0 && intPlayedTime !== 0;
if (isFifteen && debounce) {
debounce = false;
$('#result span').html(intPlayedTime);
} else {
setTimeout(function() {
debounce = true;
}, 1000);
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js" controls="controls"></script>
<video controls="" style="width:240px;height:180px; position: relative; top: -20px; float:left">
<source src="http://www.html5rocks.com/en/tutorials/video/basics/devstories.webm" type="video/webm;codecs="vp8, vorbis"" />
<source src="http://www.html5rocks.com/en/tutorials/video/basics/devstories.mp4" type="video/mp4;codecs="avc1.42E01E, mp4a.40.2"" />
</video>
<span id="result" style="position:relative; top: 70px; left: 20px">
<p><u>Updates every five seconds</u></p>
<strong>Elapsed : </strong>
<span>0</span>
</span>