boxmoe_header_banner_img

Hello! 欢迎来到悠悠畅享网!

文章导读

js 怎样用debounce创建防抖函数


avatar
作者 2025年8月23日 14

防抖函数的作用是确保事件在停止触发一段时间后才执行回调,避免频繁触发导致性能问题,1. 通过延迟执行并重新计时来减少函数调用次数;2. 适用于输入搜索、窗口调整等场景;3. 与节流的区别在于防抖只在停止触发后执行一次,而节流固定频率执行;4. 可通过添加leading和trailing选项优化;5. 测试时需验证延迟执行、多次触发只执行一次、leading和trailing行为是否正确,最终提升性能并保障用户体验。

js 怎样用debounce创建防抖函数

防抖函数的作用是在事件被触发后,延迟一段时间执行回调,如果在延迟时间内再次被触发,则重新计时。简单来说,就是确保事件在停止触发一段时间后才执行。

function debounce(func, delay) {   let timeoutId;    return function(...args) {     const context = this; // 保持上下文     clearTimeout(timeoutId);      timeoutId = setTimeout(() => {       func.apply(context, args);     }, delay);   }; }  // 示例 function handleinput(e) {   console.log('Input value:', e.target.value); }  const debouncedInputHandler = debounce(handleInput, 300); // 延迟 300 毫秒  // 在 input 元素上使用 // <input type="text" oninput="debouncedInputHandler(event)">

为什么需要防抖函数?

在某些场景下,事件会被频繁触发,例如

input

事件、

scroll

事件等。如果每次触发都执行回调,可能会导致性能问题,甚至卡顿。防抖函数可以有效地减少回调执行的次数,提高性能。 想象一下,你在搜索框输入内容,每次输入都立即发起搜索请求,服务器压力会很大。使用防抖,可以只在用户停止输入一段时间后才发起请求。

防抖函数与节流函数的区别是什么?

防抖和节流都是为了限制函数执行频率,但它们的实现方式不同。防抖是延迟执行,只在事件停止触发一段时间后才执行一次。而节流是控制函数执行的频率,保证在一定时间内只执行一次。 它们的应用场景也不同。防抖适合用于输入框搜索、窗口大小调整等场景,而节流适合用于滚动事件、鼠标移动事件等场景。 曾经我遇到一个问题,滚动事件导致页面频繁计算元素位置,造成页面卡顿。后来我使用了节流函数,将计算频率限制在每 100 毫秒一次,问题就解决了。

如何优化防抖函数?

可以考虑添加 leading 和 trailing 选项。leading 选项表示是否在延迟开始前立即执行一次回调,trailing 选项表示是否在延迟结束后执行一次回调。默认情况下,只会在延迟结束后执行一次回调。

function debounce(func, delay, options = { leading: false, trailing: true }) {   let timeoutId;   let lastArgs;   let lastThis;    const { leading, trailing } = options;    function invokeFunc(time) {     timeoutId = null;     if (lastArgs) {       func.apply(lastThis, lastArgs);       lastArgs = lastThis = null;     }   }    return function(...args) {     lastArgs = args;     lastThis = this;      if (!timeoutId) {       if (leading) {         func.apply(this, args);       }       timeoutId = setTimeout(invokeFunc, delay);     } else {       clearTimeout(timeoutId);       timeoutId = setTimeout(invokeFunc, delay);     }   }; }

如何测试防抖函数?

可以使用 Jest 或 Mocha 等测试框架来测试防抖函数。 测试用例应该覆盖以下几种情况:

  1. 事件在延迟时间内被多次触发,回调只执行一次。
  2. 事件在延迟时间内没有被再次触发,回调在延迟结束后执行。
  3. leading 选项为 true 时,回调在延迟开始前立即执行一次。
  4. trailing 选项为 false 时,回调只在延迟开始前执行一次。
// 示例 Jest 测试用例 describe('debounce', () => {   jest.useFakeTimers();    it('should call the function after the delay', () => {     const func = jest.fn();     const debouncedFunc = debounce(func, 100);      debouncedFunc();     expect(func).not.toHaveBeenCalled();      jest.advanceTimersByTime(100);     expect(func).toHaveBeenCalledTimes(1);   }); });



评论(已关闭)

评论已关闭