防抖和节流

1、防抖debounce:是指事件在触发n秒后执行,如果n秒内又被触发,时间重新计算。可以避免多次点击的问题(如按钮提交、scroll事件)
2、节流throttle:指一个时间内只执行一次,如果一个时间内,事件被触发多次,也只执行一次(拖拽、缩放、动画)

// 防抖使用debounce(func, wait, immediate)
    const debounce = function(func, wait, immediate){
        let timeId = null

        function debounced(...args){
            const context = this;
            if (immediate) {
               func.apply(context, args)
            }
            if (timeId) {
              clearTimeout(timeId)
            }
           timeId = setTimeout(() => {
               func.apply(context, args)
           }, wait)
        }

        function cancel() {
          if (timeId) clearTimeout(timeId);
          timeId=null;
        }

        debounced.cancel = cancel;
        return debounced
    }
    // 节流(时间控制)
   const throttle = function(func, wait){
       let previous = new Date().getTime();
       function throttled(...args) {
          const context = thisl
          let now = new Date().getTime();
          if (now - previous > wait) {
             previous = now;
             func.apply(context, args)    
          }
       }
       return throttled
   }

   // 节流(定时器)
   const throttle = function(func, wait) {
      let timeId = null;
      function throttled(...args) {
        const context = this;
        if (timeId) return;
        timeId = setTimeout(() => {
          func.apply(context, args)
          timeId = null
        }, wait)
      }
      return throttled
   }

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值