This code randomly plays Audio elements. Running setup twice allows you to do this with two different arrays simultaneously, which is what I want. The problem is that #stop only stops one of the arrays playing. This actually also happens if you only call setup on one array, but click #start more than once (which I also don't want). I figure this has to do with 'intervalReturn', as it would only be specified to one setInterval.
How should I write this so that multiple invocations of setup creates distinct setIntervals which can be started only once?
Alternately, if I should approach this from a totally different angle, what would be better?
EDIT: This was fixed per the suggestions below. But I'm wondering, what is going on "under the hood" with setInterval here? Why does this behavior happen at all? (Specifically: #stop stops one but not all audio elements.)
var CMajor3 = new Array ("C3","D3","E3","F3","G3","A3","B3","C4a");
var CMajor4 = new Array ("C4b","D4","E4","F4","G4","A4","B4","C5");
var intervalReturn = null;
function pickAndPlay(pitchSet){
fyshuffle (pitchSet); // the Fischer-Yates shuffle function
var tone = document.getElementById(pitchSet[0]);
tone.currentTime = 0;
tone.play();
};
function setup(time, pitchSet){
$("#start").click(function() {
console.log("startClicked");
intervalReturn = window.setInterval(pickAndPlay, time, pitchSet)
});
$("#stop").click(function() {
console.log("stopClicked");
window.clearInterval(intervalReturn)
});
};
$(document).ready(function() {
setup(2000, CMajor3);
setup(2000, CMajor4);
});
intervalReturnvariable can't hold two different values simultaneously! - try movingvar intervalReturn = nullto be the first line infunction setupif (intervalReturn !== null)as long as you explicitly set it back tonullin the#stopfunction.if (intervalReturn === null)then callsetInterval()in the#startfunction, and reset it tonullin the#stop. In other words, "if not already running then start..."