Robin
Robin

Reputation: 5486

Disable an event and again enable the event back in jQuery

I would like to show user is typing in my chat system, whenever the user is typing. I did it by keypress event:

$('#m').keypress(function(){
  socket.emit('typing', 'user is typing...');
});

However I don't want it emit a keypress event every time any key is pressed. So whenever a key is press, emit keypress event, but then disable the keypress event for 3 seconds, so that no more user is typing message is passed. And again wait for 3 seconds if no key is pressed than show the user is idle. This is the code so far:

index.html:

var typing;
typing = $('#m').on('keypress',function(){

  $('#m').unbind('keypress');

  var timeout;

  timeout = setTimeout(function() {
      socket.emit('typing', 'user is typing');
      setTimeout(function(){
        socket.emit('typing', 'idle');
      }, 3000);
    }, 3000);
  $('#m').bind('keypress');
});

It does show the user is typing after 3 seconds, and again after 3 second show that the user is idle. But if I press any key, it does not show the user is typing any more. I would really be grateful if you could help me solve this.

Upvotes: 2

Views: 92

Answers (1)

Gnucki
Gnucki

Reputation: 5133

Try that:

var disableKeyPress = false;

var typing = $('#m').on('keypress', function() {
  if (!disableKeyPress) {
    disableKeyPress = true;
    socket.emit('typing', 'user is typing');

    setTimeout(function() {
      disableKeyPress = false;

      setTimeout(function() {
        if (!disableKeyPress) {
          socket.emit('typing', 'idle');
        }
      }, 3000);
    }, 3000);
  }
});

Upvotes: 1

Related Questions