原生js面向对象实现函数节流@郝晨光

函数节流(throttle)

限制一个函数在一定时间内只能执行一次。

函数节流的使用场景

当事件不需要频繁的被触发,但是由于特定DOM事件的原因不断的触发事件的时候

在你需要用它的时候,你自然而然会知道是什么时候!

如: input事件,resize事件,scroll事件,mousemove事件,touchmove事件等只要发生操作就会频繁触发的事件

例如:

  1. scroll滚动加载,
  2. scroll滚动控制头部显示隐藏
  3. input输入内容开始搜索
  4. 防止用户高频率操作提交多次表单
  5. ·······
/**
* @class Throttle
* @param {Function} callback  需要触发的事件
* @param {Number} interval  触发事件的间隔时间
* @return {Object} 返回Throttle实例 
*/
function Throttle(callback, interval) {
    // 日常判断,保证当前是一个由Throttle生成的实例
    if(this instanceof Throttle) {
        this.callback = callback; // 保存需要执行的函数
        this.interval = interval || 500; // 设置节流时长,默认500
        this.firstTime = true; // 设置标志位,如果是第一次执行将不会节流
        this.timer = null; // 设置定时器
    }else {
        return new Throttle(callback,interval);
    }
}
// 节流函数的实现
Throttle.prototype.throttle = function (...args) {
    let _this = this; // 保存this
      // 如果是第一次执行的话,直接调用函数,并修改标志位
    if (this.firstTime) {
        this.callback.call(_this, ...args);
        this.firstTime = false;
    }
      // 如果当前存在运行中的定时器的话,直接返回,避免重复触发事件,避免重复触发定时器
    if (this.timer) {
        return false;
    }
        // 如果不存在定时器的话,定义定时器
    this.timer = setTimeout(() => {
        // 先执行off方法,关闭之前的定时器,并将this.timer赋值为null;确保在需要执行时间的时候只有一个setTimeout
        _this.off();
        // 使用call调用函数,并传入参数
        _this.callback.call(_this, ...args);
    }, _this.interval);
};
// off方法,关闭定时器
Throttle.prototype.off = function () {
    clearTimeout(this.timer);
    this.timer = null;
};

使用方法如下:

const changeScroll = e => {
    console.log(Dtae.now())
}
let myThrottle = new Throttle(changeScroll, 1000);
window.addEventListener('scroll', e => myThrottle.throttle(e), false);
结言

感谢您的查阅,代码冗余或者有错误的地方望不吝赐教;菜鸟一枚,请多关照!

你可能感兴趣的:(原生js面向对象实现函数节流@郝晨光)