Monday, June 3, 2024
 Popular · Latest · Hot · Upcoming
78
rated 0 times [  79] [ 1]  / answers: 1 / hits: 50606  / 11 Years ago, mon, october 14, 2013, 12:00:00

I have a HTML5 video element in my page. The video I want to play is having a duration of 10 minutes.



I have to play the part of the video from minute 1 to minute 5.

I can start it from a particular time by setting its currentTime property.

But how can I stop the video at a particular time jQuery or JavaScript?


More From » jquery

 Answers
17

TL;DR: Simply listen on timeupdate:



video.addEventListener(timeupdate, function(){
if(this.currentTime >= 5 * 60) {
this.pause();
}
});





The usual way to wait for something in JavaScript is to wait for an event or a timeout. A timeout is out of question in this case, the user might pause the video on his own. In this case the stop wouldn't be on your specific time, but earlier.



Checking the time regularly is also too costly: you either check too often (and therefore waste precious processing power) or not often enough and therefore you won't stop at the correct time.



However currentTime is a checkable property, and to our luck, there's the timeupdate event for media elements, which is described as follows:




The current playback position changed as part of normal playback or in an especially interesting way, for example discontinuously.




This concludes that you can simply listen on timeupdate and then check whether you've passed the mark:



// listen on the event
video.addEventListener(timeupdate, function(){
// check whether we have passed 5 minutes,
// current time is given in seconds
if(this.currentTime >= 5 * 60) {
// pause the playback
this.pause();
}
});


Keep in mind that this will pause whenever the user tries to skip past 5 minutes. If you want to allow skips and only initially pause the video beyond the 5 minute mark, either remove the event listener or introduce some kind of flag:



var pausing_function = function(){
if(this.currentTime >= 5 * 60) {
this.pause();

// remove the event listener after you paused the playback
this.removeEventListener(timeupdate,pausing_function);
}
};

video.addEventListener(timeupdate, pausing_function);

[#75004] Saturday, October 12, 2013, 11 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
jeffery

Total Points: 180
Total Questions: 114
Total Answers: 117

Location: Chad
Member since Mon, Dec 5, 2022
2 Years ago
jeffery questions
Fri, Jan 22, 21, 00:00, 3 Years ago
Wed, Dec 2, 20, 00:00, 4 Years ago
Mon, Apr 13, 20, 00:00, 4 Years ago
Mon, Feb 10, 20, 00:00, 4 Years ago
;