【发布时间】:2018-10-08 21:21:31
【问题描述】:
上下文:我正在写一个简单的油门,任务是javascript tutorial
任务:编写一个像这样工作的节流阀:
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
}
【问题讨论】:
-
谷歌
debounce js。
标签: javascript throttling