4. 手写throttle()

JavaScriptLodash Google Flipkart

中等难度  -通过 / -执行

Throttle是web应用中经常用到的技巧,通常情况下你应该使用现有的实现,比如lodash throttle()

你能够自己实现一个基本的throttle()吗?

再次说明一下,throttle(func, delay)返回一个function,这个function无论多么频繁地调用,原始的func的调用也不会超过指定的频率。

比如,这是throttle之前的调用

─ A ─ B ─ C ─ ─ D ─ ─ ─ ─ ─ ─ E ─ ─ F ─ G

按照3个单位进行throttle过后

─ A ─ ─ ─ C ─ ─ ─D ─ ─ ─ ─ E ─ ─ ─ G 

注意到

  • A因为不在任何的冷却时间,所以立即被执行
  • B被跳过了,因为B和C都在A的冷却时间里。

注意

  1. 请按照以上spec完成代码。以上逻辑和lodash.throttle()并不完全一致

  2. 因为 window.setTimeoutwindow.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'])

始终思考更好的解决办法