I have a form with an <input type=text />
and I want to call a javascript function after 5 seconds of the last key press, and every time a new key is pressed, this timer should reset and only call the function after 5 seconds.
How can I do this?
I'm using jQuery.
thanks!
To call a JavaScript function every 5 seconds continuously, we call setInterval with the function that we want to run and the interval between runs. const interval = setInterval(() => { // ... }, 5000); clearInterval(interval); to call setInterval with the callback we want to run and 5000 millisecond period.
You can execute a function by pressing the enter key in a field using the key event in JavaScript. If the user presses the button use the keydown to get know its enter button or not. If it enters the key then call the JavaScript function.
Something like this should get you started:
var timeout; $('input[type=text]').keypress(function() { if(timeout) { clearTimeout(timeout); timeout = null; } timeout = setTimeout(myFunction, 5000) })
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With