封装防抖和节流函数

防抖函数的作用是,在事件触发后等待一定时间(delay),如果在这段时间内没有再次触发事件,才执行回调函数。如果在这段时间内又触发了事件,则重新计时。

防抖函数的实现:

function debounce(func, delay) {
  let timeoutId;

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

使用示例:

function handleInput() {
  console.log('Input event debounced');
}

const debouncedHandleInput = debounce(handleInput, 300);
input.addEventListener('input', debouncedHandleInput);

一般使用在输入框搜索,按钮点击,防止重复提交,实时搜索

节流函数的实现:

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

节流函数的作用是,在一定时间间隔(delay)内只执行一次回调函数。如果在这段时间内多次触发事件,只有第一次触发会执行回调函数,后续触发会被忽略。

使用示例:

function handleScroll() {
  console.log('Scroll event throttled');
}

const throttledHandleScroll = throttle(handleScroll, 300);
window.addEventListener('scroll', throttledHandleScroll);

一般使用在页面滚动,窗口调整,鼠标移动,频繁操作限制

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值