javascript - Chrome 扩展 : Looping through an array and producing sounds based on beats per minute

标签 javascript google-chrome-extension

所以,假设我有一个这样的数组和一个循环遍历它的 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/

相关文章:

javascript - 将 2 个表单操作合并为一个表单

javascript - 为什么 console.log(error_object) 输出错误消息而不是其键/值对和方法?

javascript - 函数的封装 |面向对象的目的

javascript - 事件不会在内容脚本 Chrome 扩展程序上触发

google-chrome - 如何在 Chrome 扩展程序中访问私有(private) API

JavaScript 将一些数据包装到 json 数组中

javascript - AngularJS 服务中的自定义函数

javascript - 在 chrome 内容脚本中使用 html 模板

javascript - 注入(inject)CSS时立竿见影

javascript - 从 Chrome 扩展程序内部写入 Google 文档