Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Call a javascript function after 5 sec of last key press

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!

like image 861
Paulo Avatar asked Mar 29 '09 00:03

Paulo


People also ask

How do you run a function every 5 seconds in JavaScript?

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.

How do you run a function when a key is pressed JavaScript?

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.


1 Answers

Something like this should get you started:

var timeout; $('input[type=text]').keypress(function() {     if(timeout) {         clearTimeout(timeout);         timeout = null;     }      timeout = setTimeout(myFunction, 5000) }) 
like image 151
Crescent Fresh Avatar answered Oct 14 '22 14:10

Crescent Fresh