1

I can't figure how to add a listener to a video playback. I want it eventually to stop when it reaches to a specific play time (i.e 10 sec).

I've tried:

while( video.currentTime != timeToStop){
            video.play();
        }

But it cause the browser to hang, probably since I initiate video.play() all the time.

do while

Cause the same issue.

What should I use then?

3
  • 2
    What are you trying to do? Your code shows nothing about adding a listener. When do you want the listener to run? When the video starts? When it ends? There are events you can listen for, such as video.addEventListener("ended", someFunction);. If you want to listen for every tick, you can use the timeupdate event
    – Ian
    Jul 10, 2013 at 20:40
  • 2
    Here's an example of something you might want: jsfiddle.net/XK4NW
    – Ian
    Jul 10, 2013 at 20:57
  • Nice, that's exactly what I've needed. Thank you, do you want to post it as an answer or should I delete this question? Jul 10, 2013 at 20:59

2 Answers 2

3

To track the progress of a video, you can use the timeupdate event and check whether the currentTime property of the video has passed the max. Here's an example:

window.addEventListener("load", function () {
    var video = document.getElementById("video1"),
        timeToStop = 2;

    video.addEventListener("timeupdate", function () {
        if (this.currentTime >= timeToStop) {
            this.pause();
        }
    }, false);
}, false);

DEMO: http://jsfiddle.net/eGw52/

(where the example uses 2 seconds, not 10)

1

Video plays nicely with promises. Here is a routine which pauses at a particular point in time and returns a promise which is fulfilled when that happens (or the video pauses for some other reason, or ends).

function pause_at (video, t) {
    var promise=new Promise ();

    function reached() {
        promise.fulfill (video.currentTime);
        video.removeEventListener ("timeupdate", timeupdate);
        video.removeEventListener ("pause", reached);
    }

    function timeupdate () {
        if (video.currentTime >= t) {
            reached ();
            video.pause ();
        }
    }

    video.addEventListener ("timeupdate", timeupdate);
    video.addEventListener ("pause", reached);
    return promise;
}

Usage:

pause_at (video,60).then (function () {alert ("At 60-second mark!");});
video.play ();

Note that the video ending is also considered to be the video "pausing" (with the pause event fired), so the promise will fulfill also when the video ends.

Tweak as you wish to work with your favorite promises library. You'll need to fix this if you like to run videos backwards (negative playbackRate). :-)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.