Hey programmers, I have removed everything from my function below to just target exactly what I need help with...
After the keyup event is called, the reloadContent function will make an ajax call to gather new data from a database.
Only problem is, my servers are overloading because there is no delay from the keyup events, after every keyup the function is called.
I need a way to delay, say 1 second, before the reloadContent function is called. This way it will not run 4 times (when the user types in j o h n) but only 1 time after the user types (john), assuming they can type more than 1 character/sec.
$('#searchinput').live('keyup',function() {
reloadContent(); //execute load function
});
Any advice is appreciated
There are two ways to achieve the same: Approach 1: Using the keypress(), fadeIn(), delay() and fadeOut() methods in the jQuery library and clearTimeout() and setTimeout() methods in native JavaScript.
To delay a function call, use setTimeout() function. functionname − The function name for the function to be executed. milliseconds − The number of milliseconds. arg1, arg2, arg3 − These are the arguments passed to the function.
The keyup event occurs when a keyboard key is released. The keyup() method triggers the keyup event, or attaches a function to run when a keyup event occurs. Tip: Use the event. which property to return which key was pressed.
You can set a timeout in your keyup
handler and use jQuery's data() facility to associate its id with the element. That way, if the keyup
event is triggered again before the delay runs out, you can clear the existing timeout and schedule a new one:
$("#searchinput").live("keyup", function() {
var $this = $(this);
var timerId = $this.data("timerId");
if (timerId) {
window.clearTimeout(timerId);
}
$this.data("timerId", window.setTimeout(reloadContent, 1000));
});
$('#searchinput').live('keyup',function() {
window.setTimeout(function(){
reloadContent(); //execute load function
},1000);
});
This will make a delay, but I think you need not only delay to make what you want.
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