JS 防抖与节流

防抖与节流

 

1.防抖(debounce):

 

1.1 定义

在连续的多次触发同一事件的情况下,给定一个固定的时间间隔(假设 300 ms),该时间间隔内若存在新的触发,则清除之前的定时器并重新计时( 重新计时 300 ms )

表现为在短时间多次触发同一事件,只会执行一次函数(最后触发的那次)。

防抖函数
 

1.2 实现
function debounce (fn, wait) {
  if (typeof fn !== 'function') throw new Error('first param need a function');
  if (typeof wait !== 'number') throw new Error('second param need a number');
  let timer = null;
  // 通过闭包隐藏 debounce 函数内部变量,避免外部意外修改
  return function () {
    if (timer) {
      clearTimeout(timer);
    }
    timer = setTimeout(() => {
      fn.apply(this, arguments);
      timer = null;
    }, wait)
  }
}

问题:

1.在上面代码中,setTimeout 中使用了箭头函数,那么如果不使用箭头函数(而使用 function 普通函数)又该怎么做呢,两者之间有什么区别,这一点会在本文阐述,可以自行先思考一下。

2.如果不使用 arguments ,还有哪种书写方式。

3.为什么要使用 apply ,而不是直接执行

 

2.节流

 

2.1 定义

在固定时间间隔(一个时间周期)内,大量触发同一事件,触发事件只会执行一次。周期结束,再次触发事件则开始新的周期

节流函数

 

2.2 实现

 
1.定时器版本

function throttle(fn, delay) {
  if (typeof fn !== 'function') throw new Error('first param need a function');
  if (typeof wait !== 'number') throw new Error('second param need a number');
  let timer = null;
  return function() {
    if (timer) {
      return;
    }
    timer = setTimeout(() => {
      fn.apply(this, arguments);
      timer = null
    }, delay)
  }
}

 
2.时间戳版本

function throttle(fn, delay) {
	if (typeof fn !== 'function') throw new Error('first param need a function');
  if (typeof delay !== 'number') throw new Error('second param need a number');
  let startTime = 0;
  return function () {
    let currentTime = new Date().getTime();
    if (currentTime - startTime > delay) {
      fn.apply(this, arguments);
      startTime = currentTime;
    }
  }
}

节流中存在和防抖同样的问题,下面会通过防抖来做例子。

 

3.防抖节流中引出的问题

 
以防抖函数举例,先看 2.1 中给出的防抖函数(去掉部分代码)

function debounce (fn, wait) {
  let timer = null;
  return function () {
    if (timer) {
      clearTimeout(timer);
    }
    timer = setTimeout(() => {
      fn.apply(this, arguments);
      timer = null;
    }, wait)
  }
}

如何使用

// html
<input id="inputBox" />

// js
const inputBox = document.getElementById('inputBox');
inputBox.addEventListener('keyup', debounce((e) => {
  console.log('this:', this)
  console.log('e:', e)
  console.log('value:', inputBox.value);
}, 1000))

 
3.1 问题一:为什么要使用箭头函数

timer = setTimeout(() => {
  fn.apply(this, arguments);
  timer = null;
}, wait)

在输入框输入1,看下控制台效果:
控制台展示图片
可以看到,e 是可以拿到的,this 指向 window

然后我们把箭头函数改成 function 的普通函数:

timer = setTimeout(function() {
  fn.apply(this, arguments);
  timer = null;
}, wait)

控制台展示图片
可以看到,e 是 undefined,this 指向 window
 

要知道原因,则需要明白以下几点:

function debounce (fn, wait) {
  let timer = null;
  return function () {
		console.log('isE:', arguments)	// arguments 就是 fn 的参数
    if (timer) {
      clearTimeout(timer);
    }
    timer = setTimeout(() => {
      fn.apply(this, arguments);
      timer = null;
    }, wait)
  }
}

在 debounce 中传进一个函数,传进函数的参数是 e,实际上这个参数传递到 debounce 中返回函数的参数。这么说比较绕,我们可以打出来看看(上面代码第四行打印 isE )
 
对比图
 
可以看出,在 debounce 中的返回函数的参数,就是debounce第一个参数 fn 的参数 e 。
 
明白上面一点后,再来看箭头函数和普通函数的区别:
 
箭头函数的 this ,arguments 都取决于其外层第一个普通函数,当使用箭头函数时,this 和 arguments 都是源于 debounce 返回函数的 this 和 arguments,这样自然可以拿到对应的 e;
 
而当使用普通函数时,function的 this 和 arguments 都来源于其自身,因此 e 是肯定拿不到了,另外需要注意的是,尽管上面的 this 表现出来的都是指向 window,但本质上是不一样的。所以使用普通函数时,需要提前保存 this 。

关于 this 指向问题,可以查阅 JS 作用域,闭包,this
 

那么如果不想使用箭头函数,也可以在返回函数中提前保存 this 与 arguments,如下:

function debounce (fn, wait) {
  let timer = null;
  // 通过闭包隐藏 debounce 函数内部变量,避免外部意外修改
  return function () {
    console.log('isE:', arguments)
    if (timer) {
      clearTimeout(timer);
    }
    let _this = this;	// 提前保存 this
    let args = arguments;	// 提前保存 arguments
    timer = setTimeout(function() {
      fn.apply(_this, args); // 使用提前保存好的 this 和 arguments
      timer = null;
    }, wait)
  }
}

至此,该问题解答完毕。

 
3.2 问题二:如果不使用 arguments ,还有哪种书写方式
 

在 3.1 中我们知道了,debounce 的返回函数的参数就是 fn 的传入参数,那么可以使用扩展运算符 … 来获取参数。

function debounce (fn, wait) {
  let timer = null;
  return function (...args) {	// 使用扩展运算符
    if (timer) {
      clearTimeout(timer);
    }
    let _this = this;
    timer = setTimeout(function() {
      fn.apply(_this, args);
      timer = null;
    }, wait)
  }
}

 
3.3 问题三:为什么要使用 apply ,而不是直接执行 fn
 
apply 可以用来修改 this 指向和参数。上面两个问题中我们讲述了 this 和 arguments 的问题,在这可以理解,使用 apply 正是为了获取传入函数的 fn 的 this 和 arguments 。
 

4.防抖节流的应用场景

 
防抖与节流本质上都是为了避免短时间大量触发时间
 

防抖一般应用于:

  1. 输入框请求接口获取相关结果;
  2. window触发resize的时;

节流一般应用于:

  1. 鼠标的点击,移动等获取窗口位置,
  2. 监听滚动事件

当然,具体使用哪种,还是需要根据业务需求来选择

  • 2
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
JavaScript 中,防抖(debouncing)和节流(throttling)是两种优化高频率触发事件的方法,可以减少代码的执行次数,提高性能。 防抖 防抖是指在事件被频繁触发时,只有在一定时间内没有新的触发事件才会执行事件处理函数。在这段时间内,如果事件又被触发,则重新计时。 防抖的实现思路是:在事件处理函数执行前,设置一个定时器,如果在定时器时间内再次触发了事件,则清除原定时器并重新设置一个新的定时器,如此反复。如果在定时器时间内没有再次触发事件,则执行事件处理函数防抖的应用场景包括:搜索框输入、窗口调整等需要频繁触发事件时,可以通过防抖来减少事件处理函数的执行次数。 示例代码: ```javascript function debounce(func, delay) { let timer = null; return function () { const context = this; const args = arguments; clearTimeout(timer); timer = setTimeout(function () { func.apply(context, args); }, delay); }; } const searchInput = document.getElementById("search-input"); const searchHandler = function () { console.log("执行搜索操作"); }; searchInput.addEventListener("input", debounce(searchHandler, 500)); ``` 上面的代码中,`debounce` 函数接受一个事件处理函数和一个时间间隔作为参数,返回一个新的函数,这个新函数在被调用时会执行事件处理函数,但是在执行前会设置一个定时器,如果在时间间隔内再次被调用,则会清除原定时器并重新设置一个新的定时器。 节流 节流是指在事件被频繁触发时,只有在一定时间间隔内执行一次事件处理函数。在这段时间内,如果事件又被触发,则忽略这次触发。 节流的实现思路是:在事件处理函数执行前,判断距离上一次执行的时间间隔是否超过了指定的时间间隔,如果超过了,则执行事件处理函数并更新上一次执行时间;否则忽略这次事件触发。 节流的应用场景包括:页面滚动、DOM 元素拖拽等需要频繁触发事件时,可以通过节流来减少事件处理函数的执行次数。 示例代码: ```javascript function throttle(func, delay) { let lastTime = 0; return function () { const context = this; const args = arguments; const now = new Date().getTime(); if (now - lastTime >= delay) { func.apply(context, args); lastTime = now; } }; } const scrollHandler = function () { console.log("执行页面滚动操作"); }; window.addEventListener("scroll", throttle(scrollHandler, 500)); ``` 上面的代码中,`throttle` 函数接受一个事件处理函数和一个时间间隔作为参数,返回一个新的函数,这个新函数在被调用时会执行事件处理函数,但是在执行前会判断距离上一次执行的时间间隔是否超过了指定的时间间隔,如果超过了,则执行事件处理函数并更新上一次执行时间;否则忽略这次事件触发。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值