JS防抖与节流-定时器实现(学习记录)

一、防抖

        n秒后才执行,如果上一次触发和本次触发时间间隔小于n,重新计时。比如搜索框输入、窗口调整大小。

function debounce(fn, delay) {
    let timer = null;
    return function() {
        const context = this;
        const args = arguments;
        if (timer) clearTimeout(timer);
        timer = setTimeout(function() {
            fn.apply(context, args);
        }, delay);
    }
}
//注意两个问题
//参数传递问题:原始防抖函数fn的参数没有传递给setTimeout中的回调函数。应该将参数传递给fn,以确保正确执行被防抖的函数。
//上下文丢失问题:返回的函数中没有正确设置执行上下文(this)。如果原始防抖函数依赖于特定的执行上下文,那么这个函数可能无法按预期工作。

二、节流

        n秒内只运行一次,若在n秒内被重复触发,只有一次生效,这里添加了一个参数,实现立即执行。比如搜索联想、滚动加载、加载更多 。

function throttle(fn, delay) {
  let timer = null;
  let shouldExecute = true;

  return function() {
    const context = this;
    const args = arguments;

    if (shouldExecute) {
      fn.apply(context, args);
      shouldExecute = false;
      timer = setTimeout(() => {
        shouldExecute = true;
        timer = null;
      }, delay);
    }
  };
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值