Last active
October 2, 2015 01:24
-
-
Save baldwicc/55625e2ef91497d717dd to your computer and use it in GitHub Desktop.
Verbatim copy of underscore.js' debounce function, as a jquery plugin (amd friendly)
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 (factory) { | |
if (typeof define === 'function' && define.amd) { | |
define(['jquery'], factory); | |
} else { | |
factory(jQuery); | |
} | |
}(function ($) { | |
// Thefted from Underscore.js 1.8.3 | |
// (c) 2009-2015 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors | |
// Docs: http://underscorejs.org/#debounce | |
// 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. | |
$.fn.debounce = function(func, wait, immediate) { | |
var timeout, args, context, timestamp, result, _ = {}; | |
_.now = Date.now || function() { | |
return new Date().getTime(); | |
}; | |
var later = function() { | |
var last = _.now() - timestamp; | |
if (last < wait && last >= 0) { | |
timeout = setTimeout(later, wait - last); | |
} else { | |
timeout = null; | |
if (!immediate) { | |
result = func.apply(context, args); | |
if (!timeout) context = args = null; | |
} | |
} | |
}; | |
return function() { | |
context = this; | |
args = arguments; | |
timestamp = _.now(); | |
var callNow = immediate && !timeout; | |
if (!timeout) timeout = setTimeout(later, wait); | |
if (callNow) { | |
result = func.apply(context, args); | |
context = args = null; | |
} | |
return result; | |
}; | |
}; | |
})); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment