[ACCEPTED]-Javascript: Is it ok to call cleartimeout before settimeout?-timer

Accepted answer
Score: 26

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

  timer = setTimeout(onAir, 60000);
Score: 25

Yes you can call clearTimeout on a nullvariable.

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

timer = setTimeout(onAir,60000);
Score: 6

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

Score: 6

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

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

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

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

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

  var timer,
  duration = 60000;
  window.onAir = function onAir(){
    if (timer){
    timer = setTimeout(onAir,duration);
Score: 0

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

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

More Related questions