Shahar Galukman
Shahar Galukman

Reputation: 902

How to add listener to a video playback

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?

Upvotes: 1

Views: 4392

Answers (2)

user663031
user663031

Reputation:

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). :-)

Upvotes: 1

Ian
Ian

Reputation: 50933

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)

Upvotes: 3

Related Questions