Asynchronous Keyup Events/how To Short Circuit Sequential Keyup Events For Speed Boost
On the website I'm building for work, we have a search bar where the user can type in to search various fields stored in data on a set of elements. The problem comes in slower brow
Solution 1:
Rather than doing what you're doing, you might want to look into a concept called "debounce" which basically allows you create a function that can be invoked multiple times but will only fully execute once it hasn't been invoked for a certain amount of time.
( The following code snippet is from underscore.js )
// Returns a function, that, as long as it continues to be invoked, will not// be triggered. The function will be called after it stops being called for// N milliseconds. If `immediate` is passed, trigger the function on the// leading edge, instead of the trailing.var debounce = function(func, wait, immediate) {
var timeout;
returnfunction() {
var context = this, args = arguments;
var later = function() {
timeout = null;
if (!immediate) {
func.apply(context, args);
}
};
if (immediate && !timeout) {
func.apply(context, args);
}
clearTimeout(timeout);
timeout = setTimeout(later, wait);
};
};
Using that, you might do something like this which will only execute our expensive callback 500ms after the user stops typing
$( "#searchbox" ).keyup( debounce(function() {
// Some expensive operation here
}, 500));
There's a good plugin by Ben Alman that provides this ( http://benalman.com/projects/jquery-throttle-debounce-plugin/ ), or LoDash/Underscore provide the same functionality if you're using them.
Post a Comment for "Asynchronous Keyup Events/how To Short Circuit Sequential Keyup Events For Speed Boost"