函数节流 (throttle)
限制一个函数在一定时间内只能执行一次.
函数节流的使用场景
当事件不需要频繁的被触发, 但是由于特定 DOM 事件的原因不断的触发事件的时候
在你需要用它的时候, 你自然而然会知道是什么时候!
如: input 事件, resize 事件, scroll 事件, mousemove 事件, touchmove 事件等只要发生操作就会频繁触发的事件
例如:
scroll 滚动加载,
scroll 滚动控制头部显示隐藏
input 输入内容开始搜索
防止用户高频率操作提交多次表单
- .......
- /**
- * @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);
- Windows.addEventListener('scroll', e => myThrottle.throttle(e), false);
结言
感谢您的查阅, 代码冗余或者有错误的地方望不吝赐教; 菜鸟一枚, 请多关照!
来源: http://www.jianshu.com/p/18722e03eede