防抖和节流含义和区别

防抖和节流

防抖 (debounce)

同一个事件高频触发,n秒内所有事件只触发最后一次,例如输入框请求API

// 防抖debounce代码:
    function debounce(fn) {
      let timeout = null; // 创建一个标记用来存放定时器的返回值
      return function (arguments) {
        // 每当用户输入的时候把前一个 setTimeout clear 掉
        clearTimeout(timeout); 
        // 然后又创建一个新的 setTimeout, 
        //这样就能保证interval 间隔内如果时间持续触发,就不会执行 fn 函数
        timeout = setTimeout(() => {
          fn.apply(this, arguments);
        }, 500);
      };
    } // 处理函数
    // --------------------
    // 立即执行
    const debounce1 = function(fn, wait){
        let timer
        return function(...args){
            let immdete = !timer
            let that = this
            if(timer) clearTimeout(timer)
            timer = setTimeout(function(){
                timer = null
            },wait)
            if(immdete) fn.apply(that, args)
        }
    }

节流(throttle)

水流滴答来形容~~
n秒内高频触发事件只执行一次,例如页面滚动事件

// 定时器
function throttle(fn, interval) {
  var timer,
    __self = fn,
    firstInter = true;
  return function () {
    var args = arguments,
      _that = this;
    if (firstInter) {
      // 第一次执行无需延迟
      __self.apply(_that, args);
      firstInter = false;
    }
    if (timer) return
    timer = setTimeout(() => {
      clearTimeout(timer);
      timer = null;
      __self.apply(_that, args);
    }, interval || 500);
  };
}
// ---------------
// 时间戳
const throttle1 = function(fn, wait){
  let timer = 0
  return function(){
    let now =  Date.now()
    if(now - timer>= wait){
      timer = now
      fn.apply(this, arguments)
    }
  }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值