Yalamber Yalamber - 2 years ago 1230
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()});
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 Source

You can use timeouts to send "started typing" and "stopped typing" messages, like so:

var typing = false;
var timeout = undefined;

function timeoutFunction(){
  typing = false;

function onKeyDownNotEnter(){
  if(typing == false) {
    typing = true
    timeout = setTimeout(timeoutFunction, 5000);
  } else {
    timeout = setTimeout(timeoutFunction, 5000);


It's rough, but you should get the idea.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download