Javascript pause loop till event

1.1k views Asked by At

I have javascript question,this is part of my code:

for(var a = 0; a < videos.length; a++) {
    source.setAttribute('src', videos[a]);
    video.load();
    video.play();

    for(var b = 0; b < times[a].length; b++) {
            video.addEventListener("timeupdate", function() {
            if (this.currentTime >= times[a][b]) {
                    this.pause();
                    var answer = prompt("Please answer the question", "Answer");
                }
            }, false);
    }
}

In the array videos I have links to video and in the array times I have times when to pause video for every video differently.

My aim is to start one video then pause video at certain times and resume after the question is answered,then when the video ends start another video and ask questions again. My for loops does everything instantly and it doesn't work as I want. I came up with 2 solutions:

  1. Pause loops till event is reached.
  2. Do it with event listeners.

I have no idea how to do it any way, so I am asking for your help.

1

There are 1 answers

0
Julien Grégoire On BEST ANSWER

You should drop the for loops and work only with events. Something like this should clear out at least a few problems:

    var a = 0;
    video.src = videos[a];
    video.load();
    video.play();
    check_time();

    //instead of looping through your video, you wait until one is finished 
    //to play the next one.
    video.addEventListener("ended", function(){
        a++;
        if(a<videos.length){
            video.src = videos[a];
            check_time();

    } 
   //this will add event listener each time video is changed.     
   function check_time(){
        var b = 0;
        video.removeEventListener("timeupdate")
        video.addEventListener("timeupdate", function() {
             if (this.currentTime >= times[a][b]) {
                 this.pause();
                 var answer = prompt("Please answer the question", "Answer");
                 b++;
                }
            }, false);
      }