防抖与节流的多个实现

防抖:事件在n秒内执行一次,若再次触发则重新计算时间,常用在input即时搜索。
节流:事件在n秒内只执行一次,不管怎么再次触发,也只执行一次,常用在点击按钮。

  let content = document.getElementById('content');

  function count() {
    content.innerHTML = num++;
  }

防抖

  • 事件触发后1秒再执行(延迟执行)
  function debounce(func, wait) {
    let time;
    return function () {
      if (time) {//如果有定时器,清除
        clearTimeout(time);
      }
      time = setTimeout(() => {//没有定时器增加一个,1秒后执行函数
        func();
      }, wait);
    }
  }
content.onmousemove = debounce(count, 1000);
  • 事件触发后,立即执行,1秒后才能再次执行(立即执行)
  function debounce(func, wait) {
    let time;
    return function () {
      if (time) {
        clearTimeout(time) //取消之前任务
      }
      let flag = !time; //用来标记time状态
      time = setTimeout(() => { //增加一个定时器
      	func()
        time = null; //1秒后清空定时器
      }, wait);
      if (flag) { //第一次执行
        func();
      }
    }
  }
  content.onmousemove = debounce(count, 1000);

节流

  • 固定时间去发送请求
  function throttle(func, wait) {
    let time;
    return function () {
      if (!time) { //是否有定时器
        time = setTimeout(() => {
          time = null; //2秒后清空定时器
          func(); //执行函数
        }, wait);
      }
    }
  }
content.onmousemove= throttle(count, 2000);
  • 时间戳
  function throttle(func, wait) {
    let prev = 0; //之前的时间
    return function () {
      let now = Date.now() //现在的时间
      if (now - prev > wait) { //现在时间减去之前时间
        func();
        prev = now; //重新赋值
      }
    }
  }
  content.onmousemove= throttle(count, 2000);
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值