Created
July 25, 2011 23:06
-
-
Save xinmyname/1105493 to your computer and use it in GitHub Desktop.
Debounce keyup in JavaScript
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
(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