Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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:

$("#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});
});
like image 884
Yalamber Avatar asked May 27 '13 04:05

Yalamber


1 Answers

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.

like image 107
abject_error Avatar answered Sep 18 '22 13:09

abject_error