Skip to main content

手写节流 throttle、防抖 debounce

节流(技能冷却中)

  1. 声明定时器 timer
  2. 返回函数
    • 存在 直接返回
    • 不存在 执行函数 + 重新定时
const throttle = (fn, time) => {
let timer = null
return (...args) => {
// 直接跳过
if (timer) return
fn.call(undefined, ...args)
timer = setTimeout(() => {
timer = null
}, time)
}
}

使用方法:

const fn = throttle(() => {
console.log('hi')
}, 3000)

fn() // 打印 hi
fn() // 技能冷却中

防抖(外卖)

思路:

  1. 声明定时器 timer
  2. 返回函数
    • 存在清楚定时器
    • 重新计时(定时器内执行函数)
const debounce = (fn,time) => {
let timer = null
return (...args) => {
// 打断“技能”
if(timer){clearTimeout(timer)}
// 重新调用
timer = setTimeout(() => {
fn.call(undefined,...args)
timer = null
}, time);
}
}

使用方法:

const fn = debounce(() => {
console.log('hi')
}, 3000)

fn() // 打印 hi
fn() // 重新计时