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(…..)
}
- Fatal error: Call to undefined function wp_register_sidebar_widget() in /blog/wp-admin/includes/dashboard.php on line 31
- Why AJAX matters
- Call to undefined function: get_currentuserinfo
- Global Mosaic
- Harry Potter and the Half-Blood Prince - Book 6
- Google’s Mark Lucovsky Talks at USC
- AP Calculus Question
- SetPoint Middle-Click to Open Link in New Tab
- Automated Depersonalization of Writing
- Digg this post with WordPress
» Global Mosaic
» Google’s Mark Lucovsky Talks at USC
» Gmail Search Rocks
» Google Search: orkut


