AJ ONeal
unread,Oct 31, 2010, 4:51:51 AM10/31/10Sign in to reply to author
Sign in to forward
You do not have permission to delete messages in this group
Sign in to report message
Either email addresses are anonymous for this group or you need the view member email addresses permission to view the original message
to futures-j...@googlegroups.com
I'm creating an instant-search widget for an API that has a slow response time.
This demonstrates how to rate-limit such an instant search so that the search only occurs if a non-word character was entered (punctuation, etc) or if it has been 300ms since the last keystroke.
var key_timeout = -1;
function handleInstantSearchInput(ev) {
ev.preventDefault();
var promise = Futures.promise(),
search = "";
// clean the promise for the previous keypress
clearTimeout(key_timeout);
search = $('form#instant_search input').val();
// TODO test unicode rather than ASCII
if (!search.match(/\w$/) && search.length >= 5) {
// if the search is at least 5 chars and ends in
// a non-char (space, punctuation, etc)
// the perform the search
promise.fulfill(search);
} else {
// if the user doesn't keypress for 300 ms, search then
key_timeout = setTimeout(promise.fulfill, 300, search);
}
promise.when(function (search) {
// don't file now and then in 300ms
clearTimeout(key_timeout);
// This example is for the CampusBooks API using the AHR request object (also works in node)
campusbooks.search({ title: search }).when(function (err, xhr, data) {
if (err || data && data.repsonse && data.response.errors) {
// search didn't match, perhaps display error
return false;
}
if (data && 0 === data.response.page.results.length) {
return false;
}
// suppose the template module has already been set up
$("div#search_results").render(data, template);
});
});
}
$('body').delegate('form#instant_search', 'keyup', handleInstantSearchInput);
$('body').delegate('form#instant_search', 'submit', handleInstantSearchInput);
AJ ONeal