JS中的防抖与节流

文章内容输出来源:拉勾教育前端高薪训练营

为什么需要防抖和节流

在网页应用或app操作时,经常会有轮播图切换、点击操作、鼠标滚动(scroll)、调整窗口大小(resize)、敲击键盘输入匹配(keyup)等这些高频率事件,这类事件在触发时往往频率极高,如果不加以限制,往往会频繁的执行代码逻辑或频繁的修改DOM,此时就有可能造成程序的卡顿等问题。

浏览器默认情况下都会有自己的监听事件间隔(4ms-6ms),但是这对于运行环境来说间隔时间往往太短,为了规避次类型的问题,我们往往会使用节流(throttle)或者防抖(debounce)来进行处理。

什么是节流和防抖

  • 防抖:抖动就是短时间内高频触发,对于这个高频的操作来说,我们只希望识别一次点击,可以是人为的第一次或者是最后一次
  • 节流:对于高频操作,我们可以自己来设置频率,让本来会执行很多次的事件触发,按着我们定义的频率减少触发的次数

模拟防抖函数

/**
 * 防抖函数
 *
 * @param {*} handle 执行的事件
 * @param {*} wait 执行间隔事件
 * @param {*} immediate 是否立即执行
 */
function debounce(handle, wait, immediate) {
  if (typeof handle !== 'function') throw new Error('handle must be an function')
  if (typeof wait === 'undefined') wait =300
  if (typeof wait === 'boolean') {
    immediate = wait
    wait = 300
  }
  if (typeof immediate !== 'boolean') immediate = false
  let timer = null
  return function proxy(...args) {
    const self = this
    const init = immediate && !timer
    clearTimeout(timer)
    timer = setTimeout(() => {
      timer = null
      !immediate ? handle.call(self, ...args) : null
    }, wait);
    // 当传进来immediate为true,立即执行
    init ? handle.call(self, ...args) : null
  }
}

模拟节流函数

/**
 * 节流函数
 *
 * @param {*} handle 执行的事件
 * @param {*} wait 执行间隔事件
 */
function throttle(handle, wait) {
  if (typeof handle !== 'function') throw new Error('handle must be an function')
  if (typeof wait === 'undefined') wait =500
  let pre = 0
  let timer = null
  return function proxy(...args) {
    const now = new Date()
    const self = this
    const interval = wait - (now - pre)
    if (interval <= 0) {
      clearTimeout(timer)
      timer = null
      handle.call(self, ...args)
      pre = new Date()
    } else if (!timer) {
      timer = setTimeout(() => {
        clearTimeout(timer)
        timer = null
        handle.call(self, ...args)
        pre = new Date()
      }, interval);
    }
  }
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
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` 函数接受一个事件处理函数和一个时间间隔作为参数,返回一个新的函数,这个新函数在被调用时会执行事件处理函数,但是在执行前会判断距离上一次执行的时间间隔是否超过了指定的时间间隔,如果超过了,则执行事件处理函数并更新上一次执行时间;否则忽略这次事件触发。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值