0

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.

devjeetroy
  • 1,855
  • 6
  • 26
  • 43
  • 1
    You might take a look at [this discussion](http://stackoverflow.com/questions/729921/settimeout-or-setinterval) so that you are quite clear of the available options – AurA May 10 '12 at 04:26
  • 1
    Why don't you post some code (you can edit your post). jsFiddle is a good place to put sample Javascript code. – Steve Wellens May 10 '12 at 04:27
  • 1
    Show us your code and we can give you more specific advice. Javascript is single threaded so timers will NOT ever be executed while your javascript event handler is running so you don't need to worry about that. – jfriend00 May 10 '12 at 05:22

1 Answers1

2

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;
 }
Lior Cohen
  • 8,985
  • 2
  • 29
  • 27
  • 1
    Javascript is single threaded so a timer interval will NEVER interrupt the currently executing javascript. Thus, you do NOT need to protect your code with busy flags like you're doing. I don't see how this solves anything. – jfriend00 May 10 '12 at 05:21
  • @jfriend00: Thanks for your feedback. I am aware of this, but I got the impression that ZachSchnider was getting some weird behavior and this does answer his question, as he described it. – Lior Cohen May 10 '12 at 15:24
  • @LiorCohen Thanks for your response. I was not getting an error, your answer did clear a lot of things. – devjeetroy May 17 '12 at 02:20