KARAN GUPTA
KARAN GUPTA

Reputation: 71

How to stop video at predifined set of intervals

I wanted to make video stop video stop at a set of predefined intervals. When I am running the code it doesn't get stopped at particular time(using if(vid.currentTime ===5 )), but when when I write if(vid.currentTime >5 ) it works for some reason. But using this is creating a problem because even after clicking the continue button(I have added a continue option, I want to have a quiz after these set of intervals, I actually want to use stopTimes array), >5 condition is true , so it stops again. I tried to search for it in google but I am not getting the answer I need.

<body>
        <header>
            VIDEO QUIZ
        </header>

        <video controls height="500px" width="500px" src="https://storage.coverr.co/videos/bhnNW022Hykx6POeLwxpg02hzB9VY02xW98?token=eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJhcHBJZCI6IjExNDMyN0NEOTRCMUFCMTFERTE3IiwiaWF0IjoxNTkxNTQ2NzI1fQ.TUk0sMvleGXzgT1eSSqE9djL5FFVbCnKQBeAOoY4YtI"></video>
        <button id="continue">continue</button>

        <script src="video.js"></script>
    </body>
var vid=document.querySelector('video');

var stopTimes = [5, 10, 20];

vid.ontimeupdate= quizFunction;

var i=0;

function quizFunction (evt) {
    if(vid.currentTime ===5 ){
        vid.pause();
        console.log('javascript works');
        loadQuiz();
    }
}

function loadQuiz(){
    vid.pause();
    console.log('quiz works');

    var btn= document.querySelector('button');

    btn.style.display= 'inline';

    btn.addEventListener('click', startVideo);

}

function startVideo(){
    vid.play();
}

Upvotes: 0

Views: 157

Answers (1)

Mick
Mick

Reputation: 25471

The snippet below will stop at increments of 5 seconds - you can use an array instead of incrementing the pause timer as below if that is what you need.

You are reliant on the browser sending you timing updates at a granularity of at least one per second. In most cases I have seen this is true. I'm not sure if that behaviour is guaranteed when the browser or system is heavily loaded but that will be true for all approaches using reported timing events.

The reason for checking if the time is 'greater than' rather than 'equal to' a time is that you don't know exactly when the timing event will be triggered - i.e. you might get one at 4.9 seconds and the next at 5.6 seconds and hence miss the case where it is exactly 5 seconds.

var vid1 = document.getElementById("MyVid1");

var pauseTime = 5

vid1.ontimeupdate = function() {

    if (vid1.currentTime > pauseTime) {
      vid1.pause()
      alert ("passed " + pauseTime);
      pauseTime = pauseTime + 5
    }
    
};
<video id="MyVid1" width="320" height="176" autoplay controls preload="auto">
  <source src="http://commondatastorage.googleapis.com/gtv-videos-bucket/sample/ForBiggerBlazes.mp4" type="video/mp4">
  Your browser does not support this video format
</video>

Upvotes: 1

Related Questions