Skip to content

Instantly share code, notes, and snippets.

@szxmsu
Created July 8, 2021 14:12
Show Gist options
  • Save szxmsu/4066b6000386533eb981145e4e6de755 to your computer and use it in GitHub Desktop.
Save szxmsu/4066b6000386533eb981145e4e6de755 to your computer and use it in GitHub Desktop.
const _ = (() => {
return {
debounce: function (func, wait, leading, trailing) {
wait = wait || 0;
leading = typeof leading === 'boolean' ? leading : true;
trailing = typeof trailing === 'boolean' ? trailing : false;
if (leading && trailing) {
throw new Error();
}
let timeoutID;
return function () {
const object = this, args = arguments;
const delayed = function () {
if (trailing) {
func.apply(object, args);
}
timeoutID = undefined;
};
if (timeoutID) {
clearTimeout(timeoutID);
} else if (leading) {
func.apply(object, args);
}
timeoutID = setTimeout(delayed, wait);
};
},
throttle: function (func, wait, leading, trailing) {
wait = wait || 0;
leading = typeof leading === 'boolean' ? leading : true;
trailing = typeof trailing === 'boolean' ? trailing : false;
if (leading && trailing) {
throw new Error();
}
let timeoutID;
return function () {
const object = this, args = arguments;
const delayed = function () {
if (trailing) {
func.apply(object, args);
}
timeoutID = undefined;
};
if (timeoutID === undefined) {
if (leading) {
func.apply(object, args);
}
timeoutID = setTimeout(delayed, wait);
}
};
},
};
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment