简体   繁体   English

重置设置超时-JavaScript

[英]reset set timeout - javascript

hi there i am trying to send a message when the user starts typing and send a message again when the user stops typing... the problem is after the user stops typing it sends the stopTyping message more than once.. i figured out that the problem is with the timer in keyup function... it does not reset half way.. i guess... 您好,我尝试在用户开始键入消息时发送消息,并在用户停止键入消息时再次发送消息...问题是在用户停止键入后,它stopTyping发送了stopTyping消息..我发现问题是keyup功能中的计时器...它不会中途重置..我猜...

 var typingTimer = '';
    var hahahehehoho = "1";                //timer identifier
    var doneTypingInterval = 10000;  //time in ms, 5 second for example

    //on keyup, start the countdown
    $('#messageText').keyup(function(){
        typingTimer =  setTimeout(doneTyping, doneTypingInterval);
    });

//on keydown, clear the countdown 
$('#messageText').keydown(function(){
    clearTimeout(typingTimer);
if(hahahehehoho == "1"){    
    startTyping();
    hahahehehoho = "2";
}
});

how do i solve this problem ant help would be appreciated... thanks in advance.. :) ohh and one more thing i used the codes from Run javascript function when user finishes typing instead of on key up? 我该如何解决这个问题,在您的帮助下将获得蚂蚁的帮助... ...在此先感谢.. :)哦,还有一件事, 当用户完成键入而不是按键盘输入键时,我使用了运行javascript函数中的代码

In your keyup handler you need to cancel the timeout. 在您的keyup处理程序中,您需要取消超时。

keyup is fired at every key stroke so if you type faster enough you're enqueuing more calls to doneTyping . 每个按键都会触发keyup ,因此如果您键入的速度足够快, doneTyping更多的对doneTyping调用。

The reason for that is that within: 原因在于:

typingTimer = setTimeout(doneTyping, doneTypingInterval);

you're creating new timeouts, without clearing the old ones. 您正在创建新的超时,而不会清除旧的超时。 In the end you're only removing the last timeout. 最后,您只删除最后一个超时。

Adding: 添加:

if (typingTimer) window.clearTimeout(typingTimer); before that should solve your problem 在那之前应该解决你的问题

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

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