我正在尝试实现Lodash的_.throttle
。我知道需要返回什么(总变量),但无法弄清楚如何将所有内容放在一起。有一些摩卡测试可以帮助我理解这一点,我将在下面发布。
我已经阅读了有关该主题的几篇博客文章,并尝试将setTimeout
与一个布尔值结合使用,该布尔值确定是否需要运行setTimeout
,但是我的测试仍然失败。
/*
Throttle
Creates and returns a new, throttled version of the passed function, that, when
invoked repeatedly, will only actually call the original function at most once
per every wait milliseconds. Useful for rate-limiting events that occur faster
than you can keep up with.
Example:
let total = 0;
const count = () => ++total;
const throttleCount = throttle(count, 200);
throttleCount()
=> 1
throttleCount()
=> 1
// Wait 200ms and then:
throttleCount()
=> 2
throttleCount()
=> 2
*/
// Your code here!
let total = 0;
const count = () => {
return ++total
}
function throttle(callback, delay) {
let wait = false
return function() {
if (!wait) {
wait = true
callback()
return total
} else {
setTimeout(function() {
wait = false
}, delay)
return total
}
}
}
const throttleCount = throttle(count, 200)
throttleCount()
throttleCount()
throttleCount()
throttleCount()
throttleCount()
throttleCount()
const assert = require('assert');
describe('Throttle', () => {
it('returns a function', () => {
const exampleThrottle = throttle(() => {})
assert.equal(typeof exampleThrottle, 'function');
});
it('effectively throttles', (done) => {
let total = 0;
const count = () => ++total;
const throttleCount = throttle(count, 200);
assert.equal(throttleCount(), 1);
assert.equal(throttleCount(), 1);
// Wait 200ms and try again
new Promise(resolve => setTimeout(resolve, 200)).then(() => {
assert.equal(throttleCount(), 2);
assert.equal(throttleCount(), 2);
done()
})
});
});
我无法返回setTimeout
,因为它是未定义的。我还继续使用当前代码返回1。