js中的节流和防抖| 青训营

152 阅读3分钟

前言

在JavaScript中,可以使用节流(throttling)和防抖(debouncing)技术来优化事件处理函数的执行。这些技术主要用于处理频繁触发的事件,如窗口resize、滚动等。

节流(throttling)是指在一定时间间隔内只执行一次事件处理函数。防抖(debouncing)是指在事件连续触发的过程中,只有在一定时间间隔内没有新的事件触发时才执行事件处理函数。

简单示范

1. 节流(throttling):

function throttle(func, delay) {
  let timer = null;
  return function() {
    if (!timer) {
      timer = setTimeout(() => {
        func.apply(this, arguments);
        timer = null;
      }, delay);
    }
  };
}

// 使用节流技术处理scroll事件
window.addEventListener('scroll', throttle(function() {
  console.log('Scroll event');
}, 200));

上述代码中,throttle函数接受一个事件处理函数func和延迟时间delay作为参数,并返回一个新的函数。新的函数在被调用时,会判断是否存在定时器timer,如果不存在则设置一个新的定时器,并在延迟时间后执行事件处理函数。如果在延迟时间内再次调用新的函数,则不会重新设置定时器,从而实现了节流的效果。

2. 防抖(debouncing):

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

// 使用防抖技术处理input事件
document.getElementById('input').addEventListener('input', debounce(function() {
  console.log('Input event');
}, 500));

上述代码中,debounce函数接受一个事件处理函数func和延迟时间delay作为参数,并返回一个新的函数。新的函数在被调用时,会清除之前的定时器,并设置一个新的定时器,在延迟时间后执行事件处理函数。如果在延迟时间内再次调用新的函数,则会重新设置定时器,从而实现了防抖的效果。

通过使用节流和防抖技术,可以有效地控制事件处理函数的执行频率,提升页面性能和用户体验,现在节流和防抖已经是前端开发人员必备的技能

关于一些节流和防抖的npm包

在npm上有一些常用的包可以帮助你快速实现防抖和节流功能。以下是几个常用的npm包:

1. lodash

Lodash是一个功能强大的JavaScript实用工具库,提供了许多实用的函数,包括防抖和节流函数。你可以使用lodash.debouncelodash.throttle来实现防抖和节流功能。

// 安装lodash
npm install lodash

// 使用lodash的防抖和节流函数
import { debounce, throttle } from 'lodash';

// 使用防抖函数
const debouncedFunc = debounce(() => {
  console.log('Debounced function');
}, 200);

// 使用节流函数
const throttledFunc = throttle(() => {
  console.log('Throttled function');
}, 200);

2. debounce-throttle:

这是一个专门用于实现防抖和节流的npm包。它提供了debouncethrottle函数,使用起来非常简单。

// 安装debounce-throttle
npm install debounce-throttle

// 使用防抖和节流函数
import { debounce, throttle } from 'debounce-throttle';

// 使用防抖函数
const debouncedFunc = debounce(() => {
  console.log('Debounced function');
}, 200);

// 使用节流函数
const throttledFunc = throttle(() => {
  console.log('Throttled function');
}, 200);

这些npm包提供了方便的防抖和节流函数,帮助你快速实现这些功能,无需手动编写代码。你可以根据自己的需求选择合适的包来使用。