Skip to content

Instantly share code, notes, and snippets.

@xinmyname
Created July 25, 2011 23:06
Show Gist options
  • Save xinmyname/1105493 to your computer and use it in GitHub Desktop.
Save xinmyname/1105493 to your computer and use it in GitHub Desktop.
Debounce keyup in JavaScript
(function ($, ku)
{
var debounce = function (func)
{
var timeout;
var lastValue;
return function debounced()
{
var obj = this, args = arguments;
function delayed()
{
if (obj.value !== lastValue) {
func.apply(obj, args);
lastValue = obj.value;
}
timeout = null;
};
if (timeout)
clearTimeout(timeout);
timeout = setTimeout(delayed, 500);
};
};
jQuery.fn[ku] = function (fn) { return fn ? this.bind('keyup', debounce(fn)) : this.trigger(ku); };
})(jQuery, 'valueChanged');
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment