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:

window.setInterval(playMusic,INTERVAL);

This works all good and fine so far, but its when I try to add setTimeout events on each column:

  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? 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:

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. The i variable is updated and will be used to select a different sound for your playCol function.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top