const throttle = function(func, time) {
let timer = null;
return function(...args) {
let context = this;
// 若有 timer 這在跑不執行函數
if(timer !== null) return;
timer = setTimeout(() => {
func.apply(context, args);
// 清除函數
clearTimeout(timer);
timer = null;
}, time)
}
}
const func = (...args) => {
console.log("func is called with arguments: ", args);
}
const throttled = throttle(func, 500);
const handler = (e) => {
throttled(1, 2, 3)
}
document.addEventListener("scroll", handler)
上面這種方式沒辦法讓第一次trigger時執行,以下為修正版
/**
* @param {Function} fn
* @param {number} t
* @return {Function}
*/
var throttle = function(fn, t) {
let timer = null;
let lastArgs = null;
const execute = (context) => {
fn.apply(context, lastArgs);
lastArgs = null;
timer = setTimeout(() => {
clearTimeout(timer);
timer = null;
if(lastArgs !== null) {
execute(context);
}
}, t)
}
return function(...args) {
lastArgs = args;
if(timer !== null) {
return;
}
execute(this);
}
};
/**
* const throttled = throttle(console.log, 100);
* throttled("log"); // logged immediately.
* throttled("log"); // logged at t=100ms.
*/