gpt4 book ai didi

javascript - clearTimeout & setTimeout 函数

转载 作者:行者123 更新时间:2023-12-03 16:29:13 24 4
gpt4 key购买 nike

作为此 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 的一个版本,它运行良好。这种特殊情况有什么问题?

最佳答案

每次调用 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);
});
})();

关于javascript - clearTimeout & setTimeout 函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5223248/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com