Skip to content

Instantly share code, notes, and snippets.

@ppeeou
Created February 9, 2018 05:28
Show Gist options
  • Save ppeeou/60b956f4af0f9ed357ea1801336be5ef to your computer and use it in GitHub Desktop.
Save ppeeou/60b956f4af0f9ed357ea1801336be5ef to your computer and use it in GitHub Desktop.
debounce
var _ = {};
var restArgs = function (func, startIndex) {
startIndex = startIndex == null ? func.length - 1 : +startIndex;
return function () {
var length = Math.max(arguments.length - startIndex, 0),
rest = Array(length),
index = 0;
for (; index < length; index++) {
rest[index] = arguments[index + startIndex];
}
switch (startIndex) {
case 0: return func.call(this, rest);
case 1: return func.call(this, arguments[0], rest);
case 2: return func.call(this, arguments[0], arguments[1], rest);
}
var args = Array(startIndex + 1);
for (index = 0; index < startIndex; index++) {
args[index] = arguments[index];
}
args[startIndex] = rest;
return func.apply(this, args);
};
};
_.debounce = function (func, wait, immediate) {
var timeout, result;
var later = function (context, args) {
timeout = null;
if (args) result = func.apply(context, args);
};
var debounced = restArgs(function (args) {
if (timeout) clearTimeout(timeout);
if (immediate) {
var callNow = !timeout;
timeout = setTimeout(later, wait);
if (callNow) result = func.apply(this, args);
} else {
timeout = _.delay(later, wait, this, args);
}
return result;
});
debounced.cancel = function () {
clearTimeout(timeout);
timeout = null;
};
return debounced;
};
_.delay = restArgs(function (func, wait, args) {
return setTimeout(function () {
return func.apply(null, args);
}, wait);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment