clearTimeout if exists

The 1st one should be:

if(typeof timer_gear !== "undefined"){
  clearTimeout(timer_gear);
}

And the 2nd, but this won't work if timer_gear is not defined, so you should use the typeof one above:

if(timer_gear){
  clearTimeout(timer_gear);
}

If you only want to clear the timer held in the variable timer_gear if it exists, you can do

if (timer_gear) clearTimeout(timer_gear);

All you need to do is declare timer_gear. clearTimeout is not the problem here. To quote the MDN; Passing an invalid ID to clearTimeout does not have any effect (and doesn't throw an exception). So just add the following to the top of your code:

var timer_gear;

No need for all the if's that everyone else is suggesting.

Tags:

Javascript