How to check if video is played for consecutive 30 seconds irrespective of starting point?

Viewed 236

I have a video element in HTML

<video id="video_player" controls>
  <source src="{{object.video_file.url}}" type="video/mp4">
    Your browser does not support the video tag.
</video>

What I want is to check if video is played for consecutive 30 seconds irrespective of where it starts, to get a count.

How to write JavaScript for this in here

$("#video_player")[0].addEventListener('timeupdate',(e) =>{
 // logic
})
1 Answers

You need to keep track of when the video starts, stops, or pauses. Let's store that in a variable:

var startTime = new Date();

Make a function to reset the timer:

function reset() {
  startTime = new Date();
}

Whenever the user starts, stops or pauses the video, reset the timer:

$('#video_player')[0].addEventListener('play', reset);
$('#video_player')[0].addEventListener('pause', reset);
$('#video_player')[0].addEventListener('stop', reset);

Finally, as the video is playing, check how long it has been playing:

$('#video_player')[0].addEventListener('timeupdate', (e) => {
  let elapsedSeconds = ( new Date() - startTime ) / 1000;
  console.log( `Video has been playing for ${elapsedSeconds} seconds` );
  if ( elapsedSeconds > 30 ) {
    console.log( 'Video has been playing for more than 30 seconds!' );
    // Do something special
  }
});
Related