所以,假设我有一个这样的数组和一个循环遍历它的 for 循环:
var song = ['A', 'A', 'A'];
for (let n = 0; n < song.length; n++) {
// run 'the function' at 100 BPM...
// what I tried:
setTimeout(function() {
the function // obviously this won't work
}, beatsPerMinute);
}
我已经编写了一个函数,它接受这些字母串并将它们转换为声音。我面临的问题是时机。目前,所有声音都会同时发出。
如何尽可能准确地运行“函数”以达到每分钟节拍数?
最佳答案
setTimeout()
函数是非阻塞的,会立即返回。
var song = ['A', 'A', 'A'];
var n = 0;
function makeSound() {
setTimeout(function(){
theFunction(song[n]);
n++;
if (n < song.length)
makeSound();
}, beatsPerMinute)
}
makeSound();
关于javascript - Chrome 扩展 : Looping through an array and producing sounds based on beats per minute,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45828824/