撙节函数

观点解读

函数撙节是指肯定时间内js要领只跑一次。
生涯例子:人的眨眼睛,就是肯定时间内眨一次。

运用场景:

1、鼠标不停点击触发,mousedown(单元时间内只触发一次)。
2、监听转动事宜(它是一个高频触发对事宜),比方是不是滑到底部自动加载更多,用throttle来推断。

函数:

function throttle(fun, delay) {
    let last, deferTimer
    return function (args) {
        let that = this
        let _args = arguments
        let now = +new Date()
        if (last && now < last + delay) {
            clearTimeout(deferTimer)
            deferTimer = setTimeout(function () {
                last = now
                fun.apply(that, _args)
            }, delay)
        }else {
            last = now
            fun.apply(that,_args)
        }
    }
}
    原文作者:幸福璐
    原文地址: https://segmentfault.com/a/1190000018433085
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞