Skip to content

Instantly share code, notes, and snippets.

@TorvaldsDB
Created December 17, 2023 05:57
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save TorvaldsDB/e5c90e79e89eb5fec0da9235ea0e39cb to your computer and use it in GitHub Desktop.
Save TorvaldsDB/e5c90e79e89eb5fec0da9235ea0e39cb to your computer and use it in GitHub Desktop.
function throttle(func, delay) {
let isThrottled = false;
return function (...args) {
if (!isThrottled) {
func.apply(this, args);
isThrottled = true;
setTimeout(() => {
isThrottled = false;
}, delay);
}
};
}
// 使用示例
const throttledFunction = throttle(() => {
console.log("Throttled function executed.")
}, 500)
// 调用 throttle 函数返回的函数,会在每 500 毫秒内执行一次
throttledFunction();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment