【防抖和节流理解】

防抖和节流是常见的优化 JavaScript 性能的技术,它们通常用于处理频繁触发的事件,例如鼠标滚动、窗口调整、搜索输入等。

防抖(Debounce)和节流(Throttle)都是通过限制事件触发的频率来优化性能的,但它们的实现方式不同。

防抖

  • 防抖的实现方式是:在事件触发后,设置一个定时器,在规定的时间内如果再次触发该事件,则清除之前的定时器,重新设置一个新的定时器。只有在规定的时间内没有再次触发该事件,才会执行该事件的回调函数。

常见的防抖应用场景包括:搜索框输入、拖拽调整窗口大小等。

以下是防抖的示例代码:

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

function handleInput() {
    
    
  console.log('Input value:', this.value);
}

const input = document.querySelector('input');
input.addEventListener('input', debounce(handleInput, 500));

在这个例子中,我们使用了防抖函数 debounce 来优化 input 输入事件的性能。当用户在输入框中输入时,debounce 函数会在
500ms 后执行 handleInput
回调函数,如果在这个期间内用户再次输入,则会清除之前的定时器,并重新设置一个新的定时器,直到用户停止输入 500ms 才会执行
handleInput 回调函数。

节流

  • 节流的实现方式是:在一段时间内只能触发一次事件,如果在规定的时间内多次触发该事件,则只会执行一次该事件的回调函数。

常见的节流应用场景包括:滚动加载、窗口调整等。

以下是节流的示例代码:

function throttle(fn, delay) {
    
    
  let timer = null;
  let lastTime = null;
  return function(...args) {
    
    
    const now = new Date().getTime();
    if (lastTime && now - lastTime < delay) {
    
    
      clearTimeout(timer);
      timer = setTimeout(() => {
    
    
        lastTime = now;
        fn.apply(this, args);
      }, delay);
    } else {
    
    
      lastTime = now;
      fn.apply(this, args);
    }
  }
}

function handleScroll() {
    
    
  console.log('Window scrolled:', window.scrollY);
}

window.addEventListener('scroll', throttle(handleScroll, 500));

在这个例子中,我们使用了节流函数 throttle 来优化窗口滚动事件的性能。当用户滚动窗口时,throttle 函数会在 500ms
后执行 handleScroll 回调函数,如果在这个期间内用户再次滚动窗口,则不会执行 handleScroll 回调函数,直到
500ms 后才会再次执行。

注意:上面例子会先执行一次赋值,500ms再次执行

猜你喜欢

转载自blog.csdn.net/qq_44749901/article/details/129882472