简体   繁体   English

发出哔声的Javascript时间

[英]Javascript Timing for playing beeps

I am building a grid that will be playing sounds in HTML5/Javascript, and essentially I want it to keep repeating by looping through so I set: 我正在构建一个将以HTML5 / Javascript格式播放声音的网格,从本质上讲,我希望它通过循环不断重复播放,因此我设置了:

window.setInterval(playMusic,INTERVAL);

This works all good and fine so far, but its when I try to add setTimeout events on each column: 到目前为止,这一切都很好,但是当我尝试在每列上添加setTimeout事件时,它是可行的:

  function playMusic(){
    for(var i=0;i<GRID_SIZE;i++){
      setTimeout(playCol(i),INTERVAL/GRID_SIZE*i);
    }
  }

The reason I do it this way is so that from left to right it will play the sounds one after the other in increments. 我这样做的原因是,它将使声音从左到右依次播放。 In the developer console I can see the individual timer events firing at the right times, but the sounds aren't being played. 在开发人员控制台中,我可以看到各个计时器事件在正确的时间触发,但是声音没有被播放。 Then at the end of the interval all the sounds play at the same time. 然后,在间隔结束时,所有声音将同时播放。 So there is something I'm not understanding about why each beep isn't playing one after the other like I want it to. 因此,对于为什么每个蜂鸣声都不像我希望的那样连续播放,我有些不了解。 Does setInterval stop the code from each timeout being run until the end of the interval? setInterval会从每次超时运行到间隔结束都停止代码吗? If so is there some work around for this where I can get the beeps to play at the right times? 如果是这样,是否有一些解决方法,我可以在适当的时间发出哔哔声?

You could make your playMusic a recursive function having your counter outside: 您可以将playMusic设为递归函数,使计数器不在外面:

var i = 0;

function playMusic(){
    if( i < GRID_SIZE ){
        playCol(i);
        i++;
        setTimeout( playMusic, INTERVAL/GRID_SIZE );
    }
}

Doing this way the playMusic() function will keep calling itself until the if condition is false. 这样,playMusic()函数将继续调用自身,直到if条件为false为止。 The i variable is updated and will be used to select a different sound for your playCol function. i变量已更新,将用于为playCol函数选择不同的声音。

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

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