清除setTimeout问题

时间:2012-04-06 20:46:34

标签: javascript jquery timeout clear

我试图在键命令后将“mouseactive”设置为true不到一秒,但如果在该时间段内按下该键,我想取消该操作。但是我似乎无法弄清楚如何做到这一点。这就是我的......

$(window).keydown(function(e) {
if (e.keyCode == 40) {
        e.preventDefault();
        mouseactive = false;
        clearTimeout(t);
        var t = setTimeout("mouseActive()",800);
} else if (e.keyCode == 38) {
        e.preventDefault();
        mouseactive = false;
        clearTimeout(t);
        var t = setTimeout("mouseActive()",800);
}
});

function mouseActive() {
mouseactive = true;
}

但是这不起作用,它没有将mouseactive设置回true ...有谁能告诉我这里我做错了什么?

3 个答案:

答案 0 :(得分:2)

修改:清理冗余代码。

更多修改:确保您的var t在任何关闭之外定义,包括$(document).ready。见下文,

var t = null;

$(document).ready(function () {
   //..below code except for var t = null
});

在处理程序外声明var。

var t = null;
$(window).keydown(function(e) {
    e.preventDefault();

   if (e.keyCode == 40) {
        mouseactive = false;
   } else if (e.keyCode == 38) {
        mouseactive = false;
   }

   if (t != null) clearTimeout(t);
   t = setTimeout(mouseActive, 800);
});

function mouseActive() {
   mouseactive = true;
}

答案 1 :(得分:2)

您的问题是t在第二次运行时不在范围内。您需要将t设为全局变量。

var t;

$(window).keydown(function(e) {
if (e.keyCode == 40) {
        e.preventDefault();
        mouseactive = false;
        clearTimeout(t);
        t = setTimeout(mouseActive,800);
} else if (e.keyCode == 38) {
        e.preventDefault();
        mouseactive = false;
        clearTimeout(t);
        t = setTimeout(mouseActive,800);
}
});

function mouseActive() {
mouseactive = true;
}

P.S。不要将字符串传递给setTimeout,传递函数。传递字符串时使用eval

答案 2 :(得分:1)

你一直在重新宣布“t”,试试这个:

var t = null;  
$(window).keydown(function(e) {
    if (e.keyCode == 40) {
            e.preventDefault();
            mouseactive = false;
            if(t != null)
            {
               clearTimeout(t);
            }
            t = setTimeout("mouseActive()",800);
    } else if (e.keyCode == 38) {
            e.preventDefault();
            mouseactive = false;
            if(t != null)
            {
               clearTimeout(t);
            }
            t = setTimeout("mouseActive()",800);
    }
    });

    function mouseActive() {
    mouseactive = true;
    }