throttle(节流)和debounce(防抖)

防抖和节流都是用来控制频繁调用的问题,但是这两种的应用场景是有区别的。

throttle(节流)

有一个调用周期,在一个很长的时间里分为多段,每一段执行一次。例如onscroll,resize,500ms执行一次

// 使用时间差
function throttle (fun, wait) {
    let previous = 0

    return function (...args) {
        let now = Date.now()
        let context = this
        if (now - previous > wait) {
            fun.apply(context, args)
            previous = now
        }
    }
}

// 使用定时器
function throttle1 (func, wait) {
    let timeout
    return function (...args) {
        let context = this
        if (!timeout) {
            timeout = setTimeout(function () {
                timeout = null
                func.apply(context, args)
            }, wait)
        }
    }
}

debounce(防抖)

在一定时间内不调用,只调用一次。例如input事件,停止输入500ms之后再执行。

function debounce (fun, delay) {
    let time = null
    return function (...args) {
        let ctx = this
        clearTimeout(time)
        time = setTimeout(function () {
            fun.apply(ctx, args)
            time = null
        }, delay)
    }
}

猜你喜欢

转载自www.cnblogs.com/Juliana1992/p/10332938.html