clearTimeout和setTimeout不起作用

Rob*_*ith 2 javascript javascript-events settimeout

作为这个问题的后续,我想知道为什么这不起作用

$("#textarea").keydown(function(){
oldValue = $("#textarea").val();
});
$("#textarea").keyup(function(){
var startTimer = null;
if(startTimer) clearTimeout(startTimer);
startTimer = setTimeout(function(){
var newValue = $("#textarea").val();
// get something out of the comparison
alert(something) // alert the comparison
  oldValue = newValue;

},2000);
Run Code Online (Sandbox Code Playgroud)

所需的行为是仅在用户未输入任何内容2秒时才收到警报消息.它适用于比较部分,但是,当我按原样键入时,它不会停止警报消息.相反,我得到的警报数量与按下的按键数量相同.我试过这个创建和删除cookie的版本,它工作得很好.这个特殊情况有什么问题?

Mat*_*ley 6

在每次调用处理程序时,您都会获得一个新的startTimer(并将其初始化为null)keyup.尝试在外部范围内声明它:

(function() {
    var startTimer = null;
    var oldValue; // Declare this too, so it isn't global

    $("#textarea").keydown(function(){
        oldValue = $("#textarea").val();
    });
    $("#textarea").keyup(function(){
        if(startTimer) {
            clearTimeout(startTimer);
        }
        startTimer = setTimeout(function(){
            var newValue = $("#textarea").val();
            // get something out of the comparison
            alert(something) // alert the comparison
            oldValue = newValue;
        },2000);
    });
})();
Run Code Online (Sandbox Code Playgroud)