Skip to content

实现一个debounce函数

题目链接

https://bigfrontend.dev/problem/implement-basic-debounce

题目说明

js
let currentTime = 0

const run = (input) => {
  currentTime = 0
  const calls = []

  const func = (arg) => {
     calls.push(`${arg}@${currentTime}`)
  }

  const debounced = debounce(func, 3)
  input.forEach((call) => {
     const [arg, time] = call.split('@')
     setTimeout(() => debounced(arg), time)
  })
  return calls
}

expect(run(['A@0', 'B@2', 'C@3'])).toEqual(['C@5'])

实现一个debounce函数

题目解析

  • 需要判断join的参数个数和返回的函数给的参数个数
    • 如果大于等于还需要判断在个数内是否有占位符,如果都是数字就可以返回运算结果了
  • 如果不满足上述条件,就需要返回新的函数
  • 在新函数接收的参数中,进行占位符的替换,并且返回cur函数
js
/**
 * @param {(...args: any[]) => any} func
 * @param {number} wait
 * @returns {(...args: any[]) => any}
 */
function debounce(func, wait) {
  let timer
  return (...args) => {
    clearTimeout(timer)
    timer = setTimeout(() => {
      func(...args)
    }, wait)
  }
}

MIT Licensed