清除超时&设置超时函数
作为这个问题的后续,我'我想知道为什么这不起作用
$("#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 的一个版本,效果很好。在这个特殊案例中,有什么问题吗?
As a follow up of this question, I'd like to know why this is not working
$("#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);
The required behavior would be to get an alert message only when the user hasn't typed anything for 2 seconds. It works as for the comparison part, however, it doesn't stop the alert message when I keep typing as it should. Instead, I get the same number of alerts as the number of keys pressed.
I tried a version of this creating and deleting cookies, which it worked fine. What is wrong in this particular case?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
每次调用
keyup
处理程序时,您都会获得一个新的startTimer
(并将其初始化为null
)。尝试在外部范围内声明它:You're getting a new
startTimer
(and initializing it tonull
) on each call to yourkeyup
handler. Try declaring it in an outside scope:我认为你真正想要的是考虑使用节流或去抖风格的函数。这里有一个人编写了一个可以使用或不使用 jQuery 的程序,并且可以完全满足您的要求。我会尝试一下。
还可以看到他使用的精彩工作流程图像。我不会热链接,但值得阅读这篇文章,看看已有哪些库,这样您就可以节省一些时间。
I think what you really want is to look at using either a throttling or a debouncing style function. Here's a fella that has written one that works with or without the use of jQuery, and can do exactly what you're asking for. I would give it a try.
And also see the wonderful workflow images he uses. I won't hotlink, but it's worth a read on the article to see what library already exists so you can save yourself some time.