Yalamber Yalamber - 5 months ago 342
Node.js Question

Socket.io how to check if user is typing and broadcast it to other users

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:

$("#msg").keyup(function (e) {
if (e.keyCode == 13) {
socket.emit('send', {nickname: $('#nickname').val(), msg: $("#msg").val()});
$('#msg').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});
});

Answer

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.

Comments