The code is running okay, but I'm sure there is a more efficient way to do this. At the moment it is working okay in Firefox, but falls to pieces in Chrome. The boolean values are checked at each step, which are 110ms apart, and the outcome whether the item in the array is true or false determines whether a sound is triggered or not (unique to that array). Something in the code is stacking when Chrome spikes, which is causing all kinds of glitches and leaks... I can't seem to figure out a way to bundle this all into one check on each loop, rather than running all these if statements. Is it possible?
var loop = [{
"sound": "one",
"pattern": [true, false, false, false],
"volume": 100
},{
"sound": "two",
"pattern": [false, true, false, true],
"volume": 100
},{
"sound": "three",
"pattern": [true, true, true, true],
"volume": 100
}]
var s = 0;
function startLoop(){
if (playing === true){
setTimeout(function(){
if (typeof loop[0] !== "undefined") {
if (loop[0].pattern[s] === true){
soundset.play(loop[0].sound);
}
}
if (typeof loop[1] !== "undefined") {
if (loop[1].pattern[s] === true){
soundset.play(loop[1].sound);
}
}
if (typeof loop[2] !== "undefined") {
if (loop[2].pattern[s] === true){
soundset.play(loop[2].sound);
}
}
s++;
if (s < loop[0].pattern.length){
startLoop();
} else {
s = 0;
startLoop();
}
}, 110)
} else {return;}
};
The typeof loop[x] !== "undefined" is in place in case loops above x are not in place. The plan was to have about 10 of these running, but this way of checking each step is struggling at only three.
setInterval()or something) that's running thestartLoop()function, which also includes a timer. Running multiple timers is very risky as they easily start stacking up and cause memory leaks that way (this is most likely also the reason for your bugs, cause as they stack, multiple are running simultaneously). So be very carefull with that and try to avoid it unless you know exactly what you're doing.breakis called when the stop button is pressed. This "loop" is the only one that needs to be running (it's actually a very simple program). I guess aforloop would be better - it was the original plan but I couldn't think off the top of my head how reset back to 0 when the end of the loop was reached, and start the for loop again without calling a function. Is theifstacking acceptable then? I'll try and implement a for loop instead, and see if it runs any better!