28

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

glmxndr
  • 45,516
  • 29
  • 93
  • 118
Kenny
  • 2,150
  • 2
  • 22
  • 30
  • Thank you to everyone for the speedy answers! Also, thanks for correcting how I'm calling the function back. Learned something new there! – Kenny Jun 22 '11 at 15:23

5 Answers5

27

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

  timer = setTimeout(onAir, 60000);
Scott Rippey
  • 15,614
  • 5
  • 70
  • 85
Pointy
  • 405,095
  • 59
  • 585
  • 614
26

Yes you can call clearTimeout on a nullvariable.

Also i would suggest you change your setTimeout so it won't use eval:

timer = setTimeout(onAir,60000);
Naftali
  • 144,921
  • 39
  • 244
  • 303
8

Yes, you can call a clearTimeout on a null variable and the world won't implode.

Robert
  • 21,110
  • 9
  • 55
  • 65
6

Yes you can call clearTimeout(timer), but there are some edge cases where it may cause issues.

If timer had been previously set with some other integer value, you might be killing off a completely unrelated timer.

setTimeout just returns an integer index for the timer. If you're not sure if a timer has been previously set, you could add a check before calling clearTimeout:

if (window.timer)
{
  clearTimeout(timer);
}
...
timer = setTimeout(onAir, duration);

A solution to the possible pollution of the timer variable is to use a closure:

(function(){
  var timer,
    duration;
  duration = 60000;
  window.onAir = function onAir(){
    ...code...
    if (timer){
      clearTimeout(timer);
    }
    timer = setTimeout(onAir,duration);
  };
});
zzzzBov
  • 174,988
  • 54
  • 320
  • 367
0

Clearing a Timeout raises not problem to me (but i am not a javascript guru).

Btw, you can find intersting things (checking an existing Timeout) on this thread: Check if a timeout has been cleared?

Community
  • 1
  • 1
JMax
  • 26,109
  • 12
  • 69
  • 88