I have users making ajax call while typing. The problem is that it makes the call for every letter being typed, so I set timeout like this:
$(input).live('keyup', function(e){
setTimeout(function(){
var xx = $(input).val();
doSearch(xx);
}, 400);
});
It does wait for 400ms but then executes for every keyup. How can I change this to make the ajax call only 'once' about 400ms after the last typed letter?
(I used 'delay' in the past but that doesn't work at all with my script...)
timer = 0;
function mySearch (){
var xx = $(input).val();
doSearch(xx);
}
$(input).live('keyup', function(e){
if (timer) {
clearTimeout(timer);
}
timer = setTimeout(mySearch, 400);
});
it's better to move your function to a named function and call it multiple times, 'cause otherwise you're creating another lambda function on each keyup which is unnecessary and relatively expensive
You need to reset the timer each time a new key is pressed, e.g.
(function() {
var timer = null;
$(input).live('keyup', function(e) {
timer = setTimeout(..., 400);
});
$(input).live('keydown', function(e) {
clearTimeout(timer);
});
)();
The function expression is used to ensure that the timer
variable's scope is restricted to those two functions that need it.
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