Prevent JavaScript Keydown Event from Being Handled Multiple Times While Held Down

How to avoid holding key triggering multiple events (JS)

You could make a variable that checks if the key went up. Like this:

var isKeyDown = false;

window.addEventListener('keydown', function(e) {
if (!isKeyDown) {
isKeyDown = true;
} else {
return
}
switch (e.key) {
case 'ArrowLeft':
console.log('left');
break;
case 'ArrowRight':
console.log('right');
break;
}
});

window.addEventListener('keyup', function(e) {
isKeyDown = false;
});

How to disable repetitive keydown in JavaScript

Something like this should do the trick;

var down = false;
document.addEventListener('keydown', function () {
if(down) return;
down = true;

// your magic code here
}, false);

document.addEventListener('keyup', function () {
down = false;
}, false);

Keydown event behavior when holding down Shift key

Unfortunately, this is not a standard behaviour that you can rely on. I did a quick test on a few browsers I had installed (IE Edge, IE 11, Chrome 55, all on a windows machine), where all 3 browsers auto-repeated the keydown event for both letter keys (like A), and modifier keys (like shift), contrary to what you state your browser does.

Consistent handling of keyboard events has always been difficult across different browsers, as documented by Jan Wolter here and Peter-Paul Koch here. Wolter writes about auto-repeat:

If a key is held down long enough it typically auto-repeats, and some additional events will be triggered on each autorepeat. On Macintosh and Linux systems, modifier keys usually don't auto-repeat, but on Windows systems they do

then Wolter goes on to list various exceptions to this.

Stop key from repeating on hold. (jQuery)

Try this: http://jsfiddle.net/maniator/yFA8c/

It will only allow a letter per every 2 seconds.

Code:

var mult = false,
prev = 0;

$('.mult').keydown(function(e) {
if (!mult) {
mult = true;
prev = e.which;
setTimeout(function() {
mult = false;
}, 2000)
}
else if (prev != e.which) {
mult = false;
}
else {
return false;
}
})​;​


Related Topics



Leave a reply



Submit