I want that when a key is pressed for a long time it is not written several times
[...]
when you type fast, you do not write everything. How can I improve it?
Instead of measuring times, we have to know when the user is repeating a key. To do this, we use the property KeyboardEvent.repeat , which returns true when the key and remained pressed, generating a successive typing.
var texto=document.getElementById("texto");
texto.addEventListener('keydown', function(keyboardEvent) {
//Si se está repitiendo, ignorar
if (keyboardEvent.repeat)
keyboardEvent.preventDefault();
});
<textarea id="texto" style="width: 100%; height: 8em"></textarea>
Adapted to different versions of Internet Explorer
IE does not stop being the exception to the rule (- how weird, no?). In this case, when we associate the event with addEventListener()
, IE always returns KeyboardEvent.repeat == false
. Instead, it returns the correct value when using attachEvent ...
But there is more, attachEvent became obsolete from IE11, which left without a direct solution. So, to solve this second problem, we use the meta tag for the legacy mode X-UA-Compatible : <meta http-equiv="X-UA-Compatible" content="IE=10" />
.
And, from yapa, we add some exceptions for keys that you normally want to repeat (backspace, del, flecha, home, etc).
<!DOCTYPE html>
<html>
<head>
<title>Evitar caracteres repetidos</title>
<meta http-equiv="X-UA-Compatible" content="IE=10" />
<style>
#texto {
width: 100%;
height: 8em;
}
</style>
</head>
<body>
<textarea id="texto" placeholder="Mantenga presionada una tecla"></textarea>
<script language="javascript">
var texto = document.getElementById("texto"),
excepcionesTeclas = [
8,9,13,46, //backspace tab enter del
33,34,35,36, //PgUp/Dn home end
37,38,39,40 //flechas
];
//attachEvent para IE, addEventListener para el resto
if (texto.attachEvent) texto.attachEvent('onkeydown', noRepetirTeclas);
else texto.addEventListener('keydown', noRepetirTeclas);
function noRepetirTeclas(keyboardEvent) {
//obtener .repeat según navegador
var repeat;
if (window.event && 'repeat' in window.event)
repeat = window.event.repeat;
else
repeat = keyboardEvent.repeat;
//Si se está repitiendo, ignorar
// excepcionesTeclas deja repetir backspace, flechas, etc.
if (repeat && !~excepcionesTeclas.indexOf(keyboardEvent.keyCode)) {
if (keyboardEvent.preventDefault)
keyboardEvent.preventDefault();
else if ('returnValue' in keyboardEvent)
keyboardEvent.returnValue = false; //IE
else
return false; //IE viejo
}
}
</script>
</body>
</html>
* For IE 8- it is necessary to use the Polyfill from Array.prototype.IndexOf ().
Demo upload to a free hosting