Skip to content

Instantly share code, notes, and snippets.

@uran1980
Last active January 21, 2018 17:24
Show Gist options
  • Save uran1980/e9bf17b24fbe27b8b4add21998c015f2 to your computer and use it in GitHub Desktop.
Save uran1980/e9bf17b24fbe27b8b4add21998c015f2 to your computer and use it in GitHub Desktop.
jquery.debonce.js
/**
* @see https://stackoverflow.com/questions/28948383/how-to-implement-debounce-fn-into-jquery-keyup-event
* @see http://jsfiddle.net/bjb9s2w5/
* @see https://learn.jquery.com/plugins/basic-plugin-creation/
*
* Usage:
*
* ```
* $('input').on('keyup', $.fn.debonce(function () {
* // do some ajax request...
* }, 500));
* ```
*/
(function ($) {
'use strict';
// @see http://davidwalsh.name/javascript-debounce-function
$.fn.debonce = function (func, wait, immediate) {
var timeout;
return function () {
var context = this,
args = arguments
;
var later = function () {
timeout = null;
if (!immediate) {
func.apply(context, args);
}
};
var callNow = immediate && !timeout;
clearTimeout(timeout);
timeout = setTimeout(later, wait);
if (callNow) {
func.apply(context, args);
}
};
};
})(window.jQuery);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment