jQuery Pause or Delay for Live Ajax Search
This was fairly hard to find, so I’ll post it here for reference.
The idea is that, for live search input fields, we want to delay the Ajax call so that it fires only if the user hasn’t typed anything for half a second or so. This is because we don’t want to waste bandwidth and server resources by sending a request after every character entered by the user.
I’m trying to put together a live search input for an internal app I’m
working on and I can’t seem to figure out how to delay the ajax call to only
fire if the user hasn’t typed a character for half a second or so. That
way, the request isn’t firing after every character is entered as the user
is typing
The excellent solution came from Erik Beeson:
You basically want to have a timer that gets "canceled" if a key is pressed before it executes. Something like this: var search_timeout = undefined; $(...).bind('keyup', function() { if(search_timeout != undefined) { clearTimeout(search_timeout); } var $this = this; // save reference to 'this' so we can use it in timeout function search_timeout = setTimeout(function() { search_timeout = undefined; // do stuff with $this here }, 500); }); The 500 is the delay in ms. All that undefined checking might not be necessary, I'm just a paranoid programmer :) Good luck.
P.S. You can do stuff like this, which is quite handy:
str = $(‘#search’).val();
if(str.length >= 3){
$.ajax(…..)
}
Thanks for sharing!!
Great, this was exactly what I was looking for – thanks!
Thank you for this example. It helped me to solve very big problem with my code.
This solve my big problem! Thanks for sharing.