I am trying to setup socket.io chat server. I have gotten it up to send and receive message from server and client. I was interested in showing users if some one is typing. I know i can emit when some is typing from client to server, I can also broadcast it to other users. But will it be efficient to do that on every keyup? How do i handle such situation? Below is my code for now:
$("#textbox").keyup(function (e) {
if (e.keyCode == 13) {
socket.emit('send', {nickname: $('#nickname').val() , msg: $("#textbox").val()});
$('#textbox').val(''); }
else{
socket.emit('is typing', {nickname: $('#nickname').val()});
}
});
and on server side:
socket.on('is typing', function(data){
socket.broadcast.emit('typing', {nickname: data.nickname});
});
You can use timeouts to send "started typing" and "stopped typing" messages, like so:
var typing = false;
var timeout = undefined;
function timeoutFunction(){
typing = false;
socket.emit(noLongerTypingMessage);
}
function onKeyDownNotEnter(){
if(typing == false) {
typing = true
socket.emit(typingMessage);
timeout = setTimeout(timeoutFunction, 5000);
} else {
clearTimeout(timeout);
timeout = setTimeout(timeoutFunction, 5000);
}
}
It's rough, but you should get the idea.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With