Skip to content

Instantly share code, notes, and snippets.

@tsmd
Created March 6, 2021 07:47
Show Gist options
  • Save tsmd/b0f8fd046bf723bfa10dd12c9e33fa51 to your computer and use it in GitHub Desktop.
Save tsmd/b0f8fd046bf723bfa10dd12c9e33fa51 to your computer and use it in GitHub Desktop.
simple throttle and debounce
/**
* @param {number} delay
* @param {Function} callback
* @returns {Function}
*/
function debounce(delay, callback) {
var timer = 0;
return function () {
var self = this;
var args = arguments;
if (timer) {
clearTimeout(timer);
timer = 0;
}
timer = setTimeout(function () {
callback.apply(self, args);
}, delay);
};
}
/**
* @param {number} delay
* @param {Function} callback
* @returns {Function}
*/
function throttle(delay, callback) {
var timer = 0;
var lastExec = 0;
return function () {
var self = this;
var args = arguments;
var elapsed = Date.now() - lastExec;
function exec() {
lastExec = Date.now();
callback.apply(self, args);
}
if (timer) {
clearTimeout(timer);
timer = 0;
}
if (elapsed > delay) {
exec();
} else {
timer = setTimeout(exec, delay - elapsed);
}
};
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment