节流防抖

89 阅读1分钟

节流

初始思路

节流:类似于技能冷却中,调用之后如果处在冷却中就无法再次调用。

const sx = ()=>{
    console.log('闪现')
}
let timer = null // 定时器
let cd = false // 冷却
const throttle = ()=>{
    if(cd){
        return 
    }
    sx()
    cd = true
    timer = setTimeout(()=>{
        cd = false
    },10 * 1000)
}

// 验证
throttle()

进阶版本

优化变量,cd冷却也可以用timer来判断,同时将throttle函数变得更加的通用

const sx = ()=>{
    console.log('闪现') 
}
const throttle = (f, time) => {
    let timer = null
    // f有参数时用...args
    return (...args)=>{
        if(timer){
            return
        }
        f(...args)
        timer = setTimeout(()=>{
            timer = null
        },time)
    }
}

// 验证
const d = throttle()
d()

防抖

初始思路

防抖:类似回城打断,调用函数时,如果定时器时间还没到就重新计时

const hc = () => {
    console.log('回城')
}
let timer = null
const debounce = () => {
    if (timer) {
        clearTimeout(timer)
    }
    timer = setTimeout(() => {
        hc()
        timer = null
    }, 10 * 1000)
}

// 验证
debounce()

进阶版本

使debounce函数变得更加通用一点

const hc = ()=>{
    console.log("回城")
}
const debounce = (f, time)=>{
    let timer = null
    // f有参数时用...args
    return (...args)=>{
        if(timer){
            clearTimeout(timer)
        }
        timer = setTimeout(()=>{
            f()
            timer = null
        },time)
    }
}

// 验证
const h = debounce(hc, 3*1000)
h()