简体   繁体   English

使用setInterval和Loop播放音频

[英]Play audio with setInterval and Loop

I have this array: 我有这个数组:

var song = ['note1.mp3', 'note2.mp3', 'note3.mp3', 'note4.mp3']

for(i = 0; i < song.length; i++) {
  setInterval(function() {

    //play song[i]
    //or console.log(song[i]);

  }, 1000);

}

But this dont work, does anybody has an idea why? 但这不起作用,有人知道为什么吗? I want to play note1.mp3 then note2, note3 and note4. 我要播放note1.mp3,然后播放note2,note3和note4。

Thanks! 谢谢!

You have a scope issue. 您遇到范围问题。 There is one i for all callbacks, you have to create a scope for each i . 所有回调都有一个i ,您必须为每个i创建一个作用域。 You also have to differ the callback. 您还必须更改回调。

http://jsfiddle.net/1xy4j3eq/7/ http://jsfiddle.net/1xy4j3eq/7/

var song = ['a', 'b', 'c', 'd', 'e'];

$.each(song, function (i) {
    setTimeout(function () {
        $("div").text(song[i]);
    }, i * 1000);
});

According to your comment, the behavior you get is that you always get the last song. 根据您的评论,您得到的行为是您总是得到最后一首歌。 This is because the interval function closes on the loop counter i , so that it uses the value that i has at the time the interval function is called , which will always be the last value. 这是因为间隔函数在循环计数器i上关闭,因此它使用了调用间隔函数时 i拥有的值,该值将始终是最后一个值。

Generally, you should never setup callbacks within a loop like that. 通常,永远不要在这样的循环内设置回调。 Instead, you could do something like this 相反,您可以做这样的事情

var song = ['note1.mp3', 'note2.mp3', 'note3.mp3', 'note4.mp3']
var makeCallback = function(index) { 
    return function() {
        console.log(index);
    }
}

for(i = 0; i < song.length; i++) {
  setInterval(makeCallback(i), 1000);            
}

thus generating a different closure for each iteration 从而为每次迭代生成不同的闭包

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

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