Javascript暂停循环直到事件

Javascript pause loop till event

本文关键字:事件 循环 暂停 Javascript      更新时间:2023-09-26

我有javascript问题,这是我的代码的一部分:

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);
    }
}

在数组videos中,我有视频链接,在数组times中,我有时间为每个视频暂停视频。

我的目标是开始一个视频,然后在某些时间暂停视频,并在回答问题后继续,然后在视频结束时开始另一个视频并再次提问。我的for循环可以立即完成所有工作,但它并没有像我想的那样工作。我想出了两个解决方案:

  1. 暂停循环,直到事件到达。
  2. 使用事件监听器。

我不知道该怎么做,所以我请求你的帮助。

你应该放弃for循环,只处理事件。这样做至少可以解决几个问题:

    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);
      }