Reputation: 87
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...
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?
Upvotes: 0
Views: 233
Reputation: 4320
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
Upvotes: 2
Reputation: 8202
In your keyup
handler you need to cancel the timeout.
keyup
is fired at every key stroke so if you type faster enough you're enqueuing more calls to doneTyping
.
Upvotes: 2