clearTimeout& setTimeout不起作用

时间:2011-03-07 17:52:53

标签: javascript javascript-events settimeout

作为此question的后续内容,我想知道为什么这不起作用

$("#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);

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

2 个答案:

答案 0 :(得分: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);
    });
})();

答案 1 :(得分:1)

我认为您真正想要的是使用限制或去抖动样式功能。这是一个用或不用使用jQuery编写的一个家伙,可以完全按照你的要求去做。我试试看。

  

http://benalman.com/projects/jquery-throttle-debounce-plugin/

     

节流   使用jQuery throttle / debounce,你可以将延迟和函数传递给$ .throttle来获取一个新函数,当重复调用时,执行原始函数(在相同的上下文中并且所有参数都通过)每次延迟不超过一次毫秒。

     

限制对于调整大小和滚动等事件的处理程序的速率限制特别有用。只需看一下以下用法示例或工作限制示例就可以自己查看了!

还可以看到他使用的精彩工作流程图像。我不会热链接,但是值得阅读一篇文章,看看哪些库已经存在,这样你就可以节省一些时间。

相关问题