Created
March 6, 2021 07:47
-
-
Save tsmd/b0f8fd046bf723bfa10dd12c9e33fa51 to your computer and use it in GitHub Desktop.
simple throttle and debounce
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
/** | |
* @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); | |
}; | |
} |
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
/** | |
* @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