上下文:我正在 javascript tutorial 的任务下编写一个简单的 throttle 。
任务:编写一个像这样工作的 throttle :
function f(a) {
console.log(a)
};
// f1000 passes calls to f at maximum once per 1000 ms
let f1000 = throttle(f, 1000);
f1000(1); // shows 1
f1000(2); // (throttling, 1000ms not out yet)
f1000(3); // (throttling, 1000ms not out yet)
// when 1000 ms time out...
// ...outputs 3, intermediate value 2 was ignored
// P.S. Arguments and the context this passed to f1000 should be passed to the original f.
这是我的解决方案。奇怪的是,当我在调试控制台中逐步运行它时,它工作正常,但在其他情况下则不然。知道为什么以及如何解决它吗? (我认为它与setTimeout
有关?)
function throttle(f, ms) {
let isCoolDown = true,
queue = []
function wrapper(...args) {
queue.push(args)
if (!isCoolDown) return
isCoolDown = false
setTimeout(function() {
isCoolDown = true
if (queue[0] !== undefined) {
f.apply(this, queue.slice(-1))
queue = []
}
}, ms)
return function() {
f.apply(this, args)
queue = []
}()
}
return wrapper
}
最佳答案
一些事情:
1) 交换 isCoolDown = false
和 isCoolDown = true
2)您不需要队列,只有一个调用必须经过其他调用,其他调用会因限制而被丢弃
<小时/> function throttle(fn, ms) {
let throttle = false;
let timer;
return wrapper(...args) {
if(!throttle) { // first call gets through
fn.apply(this, args);
throttle = true;
} else { // all the others get throttled
if(timer) clearTimeout(timer); // cancel #2
timer = setTimeout(() => {
fn.apply(this, args);
timer = throttle = false;
}, ms);
}
};
}
关于javascript - throttle 不调用最后一个 throttle 参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52576307/