devjeetroy
devjeetroy

Reputation: 1945

ClearInterval() and SetInterval()

So in my javascript code, there is a part where if the user clicks on the checkbox I need to change the time delay used by setInterval(). At the moment, I used the onchange handler on the checkbox. Whenever the checkbox is changed, I call clearInterval() and setInterval(). I have the interval id as a global variable. Now if the user changes the checkbox before i have made my call to clearInterval() I expected there to be some issues, but nothing happened. Is there a better way to do this or is this way considered standard? Is there a way to check if there is an interval in existence?

PS. I'm very new to Javascript, started it about 5 hours ago.

Upvotes: 0

Views: 956

Answers (1)

Lior Cohen
Lior Cohen

Reputation: 9055

This should work:

 var myInterval = setInterval(...);

 document.getElementById('myCheckbox').onchange = function()
 {
   var func = arguments.callee;
   if (func.busy) return;
   func.busy = true;
   clearInterval(myInterval);
   myInterval = setInterval(...);
   func.busy = false;
 }

Upvotes: 2

Related Questions