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:
then Wolter goes on to list various exceptions to this.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
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
JavaScript Timestamp to Relative Time
Differencebetween Settimeout(Fn, 0) and Settimeout(Fn, 1)
Catching Errors in JavaScript Promises with a First Level Try ... Catch
JavaScript Time Zone Is Wrong for Past Daylight Saving Time Transition Rules
Typeerror: Cannot Read Property 'Setstate' of Undefined
JavaScript Curry: What Are the Practical Applications
What Exactly Can Cause an "Hierarchy_Request_Err: Dom Exception 3"-Error
Decompress Gzip and Zlib String in JavaScript
How to Sort an Associative Array by Its Values in JavaScript
How to Find a Reason Angularjs "Argument 'Myctrl' Is Not a Function, Got Undefined"
Using Raw Image Data from Ajax Request for Data Uri
Regular Expression to Match Exactly 5 Digits
Render Object Properties in React
Is There a Mechanism to Loop X Times in Es6 (Ecmascript 6) Without Mutable Variables
How to Share States Between Components Using the Usestate() Hook in React