Is there any way to make a delay in an event action? Especially for events that have more details such as keypress
. There are some examples for click
event but they aren't the solution. For example, on the whole page, when a key like a
is pressed it should appear after 1s in the input.
This could be very useful in some codes such as barcode scanner detectors or filtering user input while typing.
I tried the following code:
$(window).on('keypress', function(event) {
event.preventDefault();
setTimeout(function() {
$(document).trigger('keypress', event);
}, 1000);
})
You can use.key to get the key from the event: event.key.
https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/key
$(window).on('keypress', function(event) { event.preventDefault(); if (event.key == "a") { setTimeout(function() { $(document).find('input').val(event.key); }, 1000); } })
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <input type="text">
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.