开发者

clearTimeout if exists

timer_gear exist only in case if I press some button (until 5 sec). But there is another function it can be called 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 is not defined

Could you help me to solve this? These does not work.

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

if(timer_gear)clearTimeout(timer_gear);

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

the full code is:

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" // WO开发者_如何转开发RKS
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 answers!


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.


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);


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);
}


You need a different condition on your if:

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

or simply:

if (timer_gear)


Normally that should work:

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


if(timer_gear)clearTimeout(timer_gear);

or

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜