Ryan Coolwebs Ryan Coolwebs - 7 months ago 24
Javascript Question

clearInterval not working on shuffle function

My clearInterval function is not working from a toggle button that I have created.

$('button.shuffle').click(function() {
if(isShuffling) {
clearInterval(discoLights);
isShuffling = false;
console.log('stop shuffling')
} else {
disco = setInterval(discoLights ,3000);
isShuffling = true;
console.log('start shuffling')
}
});


I am aware that this kind of question has been asked numerous times. I did a lot of research on it within SO and I could not find solution to my problem.

Here is the JSFiddle of the code I have been working on: https://jsfiddle.net/coolwebs/zLgsdno7/7/

I have tried reordering the code on several occasions, but nothing is working. I have used setInterval and clearInterval before on page load (not set with buttons) and I have not had an issue before...

Answer

Use

clearInterval(disco);

instead of

clearInterval(discoLights);

As clearInterval takes the id which is returned by setInterval