0
点赞
收藏
分享

微信扫一扫

一篇文章理清什么是防抖、节流

一篇文章理清什么是防抖、节流_js

防抖和节流是两种常见的前端优化技术,用于限制函数的执行次数。

防抖是指在事件被触发后,等待一段时间后执行函数。如果在这段时间内事件再次被触发,那么计时器会被重置,重新等待一段时间后执行函数。这可以防止函数被频繁调用,特别是一些高频事件(如窗口调整大小、滚动等)。

function debounce(func, delay) {
  let timerId;
  
  return function(...args) {
    clearTimeout(timerId);
    
    timerId = setTimeout(() => {
      func.apply(this, args);
    }, delay);
  };
}

function handleResize() {
  console.log('Window resized!');
}

const debouncedResizeHandler = debounce(handleResize, 300);

window.addEventListener('resize', debouncedResizeHandler);

在上面的例子中,我们使用setTimeout来延迟执行传入的函数。

总的来说,防抖就是只认最后一次调用。

节流是指在一定时间间隔内,只执行一次函数。如果在这段时间内事件再次被触发,将会被忽略不执行。

function throttle(func, delay) {
  let timerId;
  let lastExecTime = 0;
  
  return function(...args) {
    const currentTime = Date.now();
    
    if (currentTime - lastExecTime >= delay) {
      func.apply(this, args);
      lastExecTime = currentTime;
    }
  };
}

function handleScroll() {
  console.log('Window scrolled!');
}

const throttledScrollHandler = throttle(handleScroll, 300);

window.addEventListener('scroll', throttledScrollHandler);

在上面的例子中,新的函数通过比较当前时间和上次执行时间来限制函数的执行。

总的来说,节流就是指定时间内只触发一次函数。


举报

相关推荐

0 条评论