6. 手写debounce()
分享给更多人
容易 -通过 / -执行
Debounce是web应用中经常用到的技巧,通常情况下你应该使用现有的实现,比如lodash debounce() 。
你能够自己实现一个基本的debounce()
吗?
比如,在debounce之前如下的调用
─ A ─ B ─ C ─ ─ D ─ ─ ─ ─ ─ ─ E ─ ─ F ─ G
经过3单位的debounce之后变为了
─ ─ ─ ─ ─ ─ ─ ─ D ─ ─ ─ ─ ─ ─ ─ ─ ─ G
注意
-
请按照以上spec完成代码。以上逻辑和
lodash.debounce()
并不完全一致 -
因为
window.setTimeout
和window.clearTimeout
并不精确。所以在test你写的代码的时候,这两个方法会被替换为静态的实现。不过不用担心,interface是一样的。
大概会按照以下的样子进行代码测试。
let currentTime = 0const run = (input) => { currentTime = 0 const calls = [] const func = (arg) => { calls.push(`${arg}@${currentTime}`) } const throttled = throttle(func, 3) input.forEach((call) => { const [arg, time] = call.split('@') setTimeout(() => throttled(arg), time) }) return calls}expect(run(['A@0', 'B@2', 'C@3'])).toEqual(['A@0', 'C@3'])