ClearTimeout if exists

timer_gear exist only if I press any button (up to 5 seconds). But there is another function that can be called at any time. In this function, I clear the timer and restart it. But first I have to check if the object exists, otherwise I get this error: Uncaught ReferenceError: timer_gear not defined

Could you help me solve this problem? They do not work.

 if(timer_gear!="undefined")clearTimeout(timer_gear); if(timer_gear)clearTimeout(timer_gear); 

EDIT1: I first sealed my question: if (! Timer => if (timer EDIT2:

full code:

 function hide_gear(){ $('#gear_div').animate({opacity: 0}, 1000); delete timer_gear; //EDIT3: destroy object } 

...

 /*gear*/ $('#gear').click(function(){ $('#gear_div').animate({ opacity: 1, }, 1000, function() { timer_gear = setTimeout("hide_gear();",5000); }); }); $('#gear').mousemove(function(){ if( ? ? ? ) { clearTimeout(timer_gear); timer_gear = setTimeout("hide_gear();",5000); } }); 

Results:

 timer_gear// Uncaught ReferenceError timer_gear is not defined timer_gear != undefined // Uncaught ReferenceError: timer_gear is not defined typeof timer_gear !== "undefined" // WORKS typeof timer_gear != "undefined" // WORKS, just tired it var timer_gear; //at the begining - WORKS, but I did not wanted a new variable if its not necessary 

Thank you for your answers!

+12
source share
6 answers

The first should be:

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

And second, but this will not work if timer_gear not defined , so you should use typeof above :

 if(timer_gear){ clearTimeout(timer_gear); } 
+4
source

All you have to do is declare a timer_gear . clearTimout is not a problem here. Quote MDN ; Passing an invalid identifier to clearTimeout has no effect (and does not raise an exception). So just add the following to the beginning of your code:

 var timer_gear; 

It is not necessary that everyone, if everyone else offered.

+44
source

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

 if (timer_gear) clearTimeout(timer_gear); 
+6
source

You need another condition for your if :

 if (typeof(timer_gear) !== "undefined") 

or simply:

 if (timer_gear) 
0
source

Usually this should work:

 timer_gear = false; if(timer_gear != false){ clearTimeout(timer_gear); } 
0
source
 if(timer_gear)clearTimeout(timer_gear); 

or

 if(timer_gear != undefined)clearTimeout(timer_gear); 
0
source

Source: https://habr.com/ru/post/909039/


All Articles