Skip to content

Instantly share code, notes, and snippets.

@JimBlaney
Created April 23, 2017 23:31
Show Gist options
  • Save JimBlaney/81b346b88b8c8fd52da0dc1bcb01ed78 to your computer and use it in GitHub Desktop.
Save JimBlaney/81b346b88b8c8fd52da0dc1bcb01ed78 to your computer and use it in GitHub Desktop.
JavaScript throttle/debounce functions as a module
(function (global) {
'use strict';
var eventUtils = {
debounce: function (fn, delay) {
var timer = null;
return function () {
var context = this, args = arguments;
clearTimeout(timer);
timer = setTimeout(function () {
fn.apply(context, args);
}, delay);
}
},
throttle: function (fn, threshhold, scope) {
threshhold || (threshhold = 250);
var last,
deferTimer;
return function () {
var context = scope || this;
var now = +new Date,
args = arguments;
if (last && now < last + threshhold) {
// hold on to it
clearTimeout(deferTimer);
deferTimer = setTimeout(function () {
last = now;
fn.apply(context, args);
}, threshhold);
} else {
last = now;
fn.apply(context, args);
}
}
}
};
// AMD support
if (typeof define === 'function' && define.amd) {
define(function () { return eventUtils; });
// CommonJS and Node.js module support.
} else if (typeof exports !== 'undefined') {
// Support Node.js specific `module.exports` (which can be a function)
if (typeof module !== 'undefined' && module.exports) {
exports = module.exports = eventUtils;
}
// But always support CommonJS module 1.1.1 spec (`exports` cannot be a function)
exports.eventUtils = eventUtils;
} else {
global.eventUtils = eventUtils;
}
})(this);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment