手写一个事件节流函数

节流

规定一个单位时间,在这个单位时间内,只触发一次事件的回调函数执行,如果在同一个单位内该事件被触发多次,只有一次触发生效。

应用场景

  1. 鼠标连续点击触发,只在单位时间内触发一次
  2. 在页面无线加载场景下,需要用户在滚动页面时,每隔一段时间发送一次网络请求,而不是在用户停止滚动页面之后在发送请求
  3. 监听滚动事件,比如滑到页面底部加载更多
  4. 拖拽场景,防止高频率触发影响位置变动
  5. 缩放场景,监听浏览器resize

节流函数

1.使用underscore.js插件

该插件可以进行节流

        content.onmousemove = _.throttle(doSome, 2000, {
    
    
            //第一次执行
            leading: true, 
             //最后一次不执行
            trailing: false
        })

2.使用时间戳实现(第一次触发,最后一次不触发)

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

3.使用定时器实现(第一次不会触发,最后一次触发)

function throttle(func, wait) {
    
    
    let that, args, timeout;

    return function() {
    
    
        that = this;
        args = arguments;
        // 定时器不存在的时候在执行
        if (!timeout) {
    
    
            timeout = setTimeout(() => {
    
    
                timeout = null;
                func.apply(that, args)
            }, wait)
        }
    }
}

4.使用时间戳和定时器相结合实现(第一次执行,最后一次也执行)

function throttle(func, wait) {
    
    
    let that, args, timeout;
    let old = 0; //时间戳
    return function() {
    
    
        that = this;
        args = arguments;
        let now = new Date().valueOf();
        if (now - old > wait) {
    
    
            if (timeout) {
    
    
                clearTimeout(timeout);
                timeout = null;
            }
            func.apply(that, args);
            old = now;
        } else if (!timeout) {
    
    
            // 定时器不存在的时候在执行
            timeout = setTimeout(() => {
    
    
                old = new Date().valueOf();
                timeout = null;
                func.apply(that, args)
            }, wait)
        }
    }
}

具体使用可参考防抖函数的使用*[https://blog.csdn.net/weixin_57399180/article/details/118020652?spm=1001.2014.3001.5501*]

防抖和节流可是面试题的重点哦!!!

猜你喜欢

转载自blog.csdn.net/weixin_57399180/article/details/118059610
今日推荐