简体   繁体   English

addEventListener 在 while 循环中工作吗?

[英]Does addEventListener work in a while loop?

I am trying to loop through a number of elements to change the audio source of a single audio element, play it, and once ended, change the new src and play it until the loop has gone through all elements:我正在尝试遍历多个元素以更改单个音频元素的音频源,播放它,一旦结束,更改新的 src 并播放它,直到循环遍历所有元素:

var contentAudio = new Audio();;

function audioLoop(index, audioModel) {

    while (index < audioModel.length) {
        var audio = contentAudio;
        audio.src = audioModel[index].src;
        audio.play()
        audio.addEventListener('ended', 
            function () {
                index++;
            });
    }
    console.log('done');

}

It seems that adding the event listener is not working.似乎添加事件侦听器不起作用。 The audio does not play and I am stuck in an endless loop.音频无法播放,我陷入无限循环。 The audio ended event is never triggered.音频结束事件永远不会被触发。 Am I doing anything wrong?我做错了什么吗? Is there a better alternative?有更好的选择吗?

The while loop is synchronous so it doesn't wait for your ended event. while循环是同步的,因此它不会等待您的ended事件。 Here is what I'm suggesting:这是我的建议:

var contentAudio = new Audio();

function audioLoop(index, audioModel) {

    (function process(done) {
      if (index >= audioModel.length) {
        done(); return;
      }
      var audio = contentAudio;
      audio.src = audioModel[index].src;
      audio.play()
      audio.addEventListener('ended', function () {
        index++;
        process(done);
      });
    })(function () {
      console.log('done');
    });

}

Also is audioModel an array. audioModel一个数组。 If so I think you should be using audioModel[index].src instead of audioModel.src .如果是这样,我认为您应该使用audioModel[index].src而不是audioModel.src

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM