手写节流throttle, 防抖debounce

29 阅读1分钟

1.节流 throttle

1.概念:节流可以理解成王者荣耀里面的技能 闪现,大家都知道闪现是120s一个,放完后,只能等120s之后了

2.使用场景:用户频繁点击按钮,有个冷却时间,在这段时间内只能用一次

3.代码实现:


const d = () => {

console.log("闪现成功")

}

const throttle = ( f,time ) =>{

let 冷却中 = false

let timer = null

return ( ...args ) =>{

if( 冷却中 ) { return }

f.call( undefined, ...args)

冷却中 = true

timer = setTimeout( ()=>{

冷却中 = false

},time)

}

}

const d2 = throttle( d, 120 *1000) // 120s一个闪现

d2() //执行后,会打印 闪现成功,但是在接下来120s再执行,就不会打印,因为技能冷却中

4.控制台打印

image.png

二. 防抖 debounce

1.概念:防抖就是回城被打断,然后要重新执行回城动作

2.使用场景:用户频繁进行拖动操作,比如拖动窗口

3.代码


const f = ()=>{
    console.log('回城')
}

const debounce = (f,time) =>{
    let timer = null
    return (...args)=>{
         if(timer){
             clearTimeout(timer)
         }
         timer = setTimeout(()=>{
             f.call(undefined,...args)
             timer = null
         },time)
    }
}

const tp = debounce(f,3000) //假设会城要3s钟



4.执行结果截图:

image.png