Last active
January 21, 2018 17:24
-
-
Save uran1980/e9bf17b24fbe27b8b4add21998c015f2 to your computer and use it in GitHub Desktop.
jquery.debonce.js
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
/** | |
* @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