手写节流函数

发布时间:2022-07-02 发布网站:脚本宝典
脚本宝典收集整理的这篇文章主要介绍了手写节流函数脚本宝典觉得挺不错的,现在分享给大家,也给大家做个参考。

节流原理

如果持续的触发事件,每隔一段时间,只执行一次事件

应用场景

  1. DOM元素的拖拽功能实现
  2. 射击游戏
  3. 计算鼠标移动的距离
  4. 监听scroll滚动事件

underscore中的防抖函数_.throttle

contant.onmousemove = _.throttle(doSomeThing, 2000, {
    leading: false, //禁用首次执行,即禁用第一次调用事件函数立即执行
    trailing: false //禁用最后一次执行
    //二者不能都为false,将会产生bug
});

防抖函数实现原理:时间戳 + 定时器

1. 时间戳实现 第一次触发,最后一次不触发 { leading:true, training: false }

function throttle(func, wait){
    let context, args;
    //之前的时间戳
    let old = 0;
    return function(){
        context = this;
        args = arguments;
        //获取当前时间戳
        let now = new Date().valueOf();
        if(now-old > wait){
            // 立即执行
            func.apply(context,args);
            old = now;
        }
    }
}

2. 定时器实现 第一次不触发,最后一次触发{ leading:false, training: true }

function throttle(func, wait){
    let context, args, timeout;
    return function(){
        context = this;
        args = arguments;
        if(!timeout){
            timeout = setTimeout(()=>{
                timeout = null;
                func.apply(context,args);
            },wait)
        }
    }
}

3.时间戳+定时器

function throttle(func, wait, options){
    let context, args, timeout;
    let old = 0; //时间戳
    if(!options) options = {};

    let later = function() {
        old = new Date().valueOf();
        timeout = null;
        func.apply(context,args);
    }
    return function(){
        context = this;
        args = arguments;
        let now = new Date().valueOf();
        if(options.leading === false){
            old = now;
        }
        if(now-old > wait){
            //第一次直接执行
            if(timeout){
                clearTimeout(timeout);
                timeout = null;
            }
            func.apply(context, args);
            old = now;
        }else if(!timeout && options.trailing !== false){
            //最后一次会执行
            timeout = setTimeout(later, wait);
        }
    }
}

脚本宝典总结

以上是脚本宝典为你收集整理的手写节流函数全部内容,希望文章能够帮你解决手写节流函数所遇到的问题。

如果觉得脚本宝典网站内容还不错,欢迎将脚本宝典推荐好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。
标签: