繁体   English   中英

clearTimeout & setTimeout 函数

[英]clearTimeout & setTimeout function

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

$("#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 的版本,它运行良好。 在这种特殊情况下有什么问题?

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

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

我认为您真正想要的是查看使用节流或去抖动风格的功能。 这是一个写了一个可以使用或不使用 jQuery 的人,并且可以完全满足您的要求。 我会尝试一下。

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

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

节流对于限制处理程序对调整大小和滚动等事件的执行速度特别有用。 只需看看下面的使用示例或工作节流示例,就可以亲眼看看!

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM