How can I avoid autorepeated keydown events in JavaScript?

Use event.repeat to detect whether or not the event is repeating. You could then wait for “keyup” before allowing the handler to execute a second time.

var allowed = true;

$(document).keydown(function(event) { 
  if (event.repeat != undefined) {
    allowed = !event.repeat;
  }
  if (!allowed) return;
  allowed = false;
  //...
});

$(document).keyup(function(e) { 
  allowed = true;
});
$(document).focus(function(e) { 
  allowed = true;
});

Leave a Comment