[javascript核心-13] 实现高质量的节流函数

97 阅读1分钟

本文github地址:JavaScript_Everything 大前端知识体系与面试宝典,从前端到后端,全栈工程师,成为六边形战士


何为节流

设定固定时间内只会执行一次,无论用户触发多少次

与防抖的区别

防抖需要取消用户频繁的操作,不断的延后,并重新开始;但节流按照固定的频率执行事件函数。

应用场景

用户输入:固定时间触发一次,发送一次网络请求

游戏:固定时间内用户的操作只相应一次

基本实现

核心逻辑是计算出时间间隔

function throttle(callback, interval){
    let startTime = 0
    const _throttle = function(){
        // 通过时间计算确定频率
        const nowTime = new Date()
        let waitTime = interval - (nowTime - startTime)
        if(waitTime <= 0){
            callback()
            startTime = nowTime
        }
    }
    return _throttle
}

优化 1 - 修正this指向

function throttle(callback, interval){
    let startTime = 0
    const _throttle = function(...args){
        // 通过时间计算确定频率
        const nowTime = new Date()
        let waitTime = interval - (nowTime - startTime)
        if(waitTime <= 0){
            callback.apply(this, args)
            startTime = nowTime
        }
    }
    return _throttle
}

优化 2 - 增加控制立即执行的功能

默认第一次触发是立即执行的,但我们可以增加对第一次立即触发的控制。

function throttle(callback, interval, immediate = true){
    let startTime = 0
    const _throttle = function(...args){
        const nowTime = new Date()
        // 对立即执行进行控制
        if(!immediate && startTime === 0){
            startTime = nowTime
        }
        // 通过时间计算确定频率
        let waitTime = interval - (nowTime - startTime)
        if(waitTime <= 0){
            callback.apply(this, args)
            startTime = nowTime
        }
    }
    return _throttle
}

本文github地址:JavaScript_Everything 大前端知识体系与面试宝典,从前端到后端,全栈工程师,成为六边形战士