ICode9

精准搜索请尝试: 精确搜索
首页 > 其他分享> 文章详细

手写节流函数

2021-10-23 14:02:49  阅读:201  来源: 互联网

标签:old 节流 args timeout let context false 手写 函数


节流原理

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

应用场景

  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);
        }
    }
}

标签:old,节流,args,timeout,let,context,false,手写,函数
来源: https://www.cnblogs.com/ITwj-115/p/15430240.html

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有