Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript: Is it ok to call cleartimeout before settimeout?

Tags:

I have a function that sets a timer, and calls itself back upon expiration of the timer.

What I'd like to know is if it is bad practice to clear the timer at the top of the function.

The reason for this is because I will be calling that function asynchronously from time to time, and if I don't clear the timer first, I'll have two running simultaneously.

I realize that I can clear the timer right before I make the other call to the function, but I'm wondering if it will cause problems in any browser if I just keep the cleartimeout call inside the function which contains the timer.

One other thought - Can I test the timer variable before making the cleartimeout call, to see if it is a timer?

Here is some example code:

function onAir(){      // reset timer       clearTimeout(timer);      $.getJSON("http://mywebsite.com?format=json&callback=?",function(data){         if(data.result == '1'){             do stuff here            }         else{             do other stuff here         }        });      // start timer     timer = setTimeout("onAir()",60000); }  

Thanks for sharing your brain with me!

Kenny

like image 267
Kenny Avatar asked Jun 22 '11 15:06

Kenny


People also ask

Do you need to clearTimeout after setTimeout?

No, you don't need to use clearTimeout if you intend for the timeout to be executed. The clearTimeout method is only used to stop timeouts from being executed. You can stop a timeout even if it has a time of 0 ms, because it won't be executed until you exit your function and return the control to the browser.

Can we clearTimeout inside setTimeout?

clearTimeout() inside setTimeout() method not working in JS It does "work", but your logic is incorrect. After you called clearTimeout you are calling setTimeout again. Instead of calling clearTimeout you should just exit the function.

Do you need to call clearTimeout?

You don't actually need to use clearTimeout , you only use it if you wish to cancel the timeout you already set before it happens. It's usually more practical to use clearInterval with setInterval because setInterval usually runs indefinitely.

Does clearTimeout stop execution?

Methods setTimeout(func, delay, ... args) and setInterval(func, delay, ... args) allow us to run the func once/regularly after delay milliseconds. To cancel the execution, we should call clearTimeout/clearInterval with the value returned by setTimeout/setInterval .


1 Answers

Yes, that's fine. Also, you should call "setTimeout()" like this:

  timer = setTimeout(onAir, 60000); 
like image 185
Pointy Avatar answered Oct 19 '22 12:10

Pointy