I'm currently developing a live search for my website and I want to decrease some unnecessary request with some simple jQuery (of course I have a back-end-flood-control). I've got a keydown-event-listener for my search-field. This listener currenty only fires the ajax command for the PHP search-function if val().length
is >= 3.
But now I want an additional condition. So when the length is >= 3, I want to wait for about 0.5s or so if the user is performing another keypress. If he does, the function should not be called and I want the listener to wait another 0.5s and wait again for more user-input, and so on. How do I realize a function like that?
var timeout;
$('#yousearchbox').on('keyup',function(){
//if you already have a timout, clear it
if(timeout){ clearTimeout(timeout);}
//start new time, to perform ajax stuff in 500ms
timeout = setTimeout(function() {
//your ajax stuff
},500);
})
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