I am making a chat, and I have a system that notifies the users when the other user is typing, all works good, however now I want to make it even better so it doesn’t bug up, and to do this I need to sent an event through the server (Using websockets), so I want this not to fire every time a user presses a key, but send it each 4 seconds or so that the user is typing but I can’t get what I’ve tried to work quite right, it seems to sort of work, but after a few seconds it’s being fired every keypress, because the timer gets messed up or something.
var stillTyping = 0;
$("body").on("keypress",".chat-form .chat-textarea",function(event) {
if(!userTyping||stillTyping>3)
{
friendID = $(this).attr("rel");
var currentID = cookie("login");
socket.emit('userChatTyping', friendID, currentID);
setInterval(function(){stillTyping++},1000);
stillTyping = 0;
}
clearTimeout(inputTimer);
userTyping = true;
inputTimer = setTimeout(finishedTyping, 1200);
});
You set an interval here
so this function will get called every thousand seconds, regardless of whether the user stops typing.
You need to clear this interval when the user has stopped typing
You might want to use timeouts instead