Reputation: 2834
Suppose I have the following code:
var sequencerRun = function(){
var currentTime = 0
var starting = 200
for(var k = 0; k < 16; k++){
$(".instrument td .beat" + k).each(function(){
setTimeout(blinker, currentTime,$(this));
})
currentTime += starting
}
}
var timerId;
var runSeq = function(){
setInterval(sequencerRun,3200);
}
$('.play').click(function(){
sequencerRun();
runSeq();
})
$('.stop').click(function(){
//??????
})
I am using this code as a way to run through my sequencer in a drum machine I am building. sequencerRun
runs through a matrix, built using a table
, and checks each column to see if it will play the corresponding sound. What I am doing is scheduling checks at each column(1 - 16) at different times (0,200,400,...,1600) respectively with setTimeout(blinker, currentTime,$(this));
. The problem is that these events are scheduled right away on each invocation on sequencerRun
. So if sequencerRun
gets invoked and I click at time 850, I want all of the setTimeouts with times 1000, 1200, 1400, 1600 to not invoke blinker
. Is there anyway to do this?
Upvotes: 0
Views: 55
Reputation: 30557
Store the interval in a variable
and use clearInterval()
var interval;
var runSeq = function(){
interval = setInterval(sequencerRun,3200);
}
$('.play').click(function(){
sequencerRun();
runSeq();
})
$('.stop').click(function(){
clearInterval(interval);
});
Also, for the setTimeout
itself
setTimeout(blinker, currentTime,$(this));
use a flag
var stopped = false;
$('.stop').click(function(){
clearInterval(interval);
stopped = true;
});
and in the callback
function blinker(){
if(stopped){
return;
}
//...else, continue normal execution
}
Upvotes: 3