clearTimeout如果存在 [英] clearTimeout if exists

查看:94
本文介绍了clearTimeout如果存在的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

timer_gear 仅在我按某个按钮(直到5秒)的情况下才存在。但是可以随时调用另一个函数。在此功能中,我清除计时器并重新启动它。但首先我必须检查对象是否存在,否则我收到此错误:
未捕获的ReferenceError:未定义timer_gear

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:
首先我拼错了我的问题:if(!timer => if(timer)
EDIT2:

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

完整代码为:

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

谢谢你的答案!

推荐答案

第一个应该是:

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

第二个,但是这个不起作用如果 timer_gear 未定义,所以你应该使用 typeof 一个

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

这篇关于clearTimeout如果存在的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆