JS防抖节流篇----节流

节流:

         频繁触发,但是触发时间内一段时间执行一次

常见应用场景:

         resize  scroll

//理解版
<body>
    <input type="text">
    <script>
        const ipt = document.querySelector('input')
        // 节流:一定时间内执行一次
        let timer = null
        ipt.oninput = (e) => {
            if (!timer) {
                timer=setTimeout(() => {
                    console.log(e.target.value);
                    timer = null
                }, 2000);
            }
        }
    </script>
</body>
// 时间戳,第一次触发立即执行
    function throttle(fn, interval) {
      let last = 0
      return function () {
        let now = Date.now()
        // now - last两次触发的时间间隔
        if (now - last >= interval) {
          last = now
          fn.apply(this, arguments);
        }
      }
    }
    function handle() {
      console.log(Math.random());
    }
    const throttleHandle = throttle(handle, 1000)
    throttleHandle()
    throttleHandle()
    throttleHandle()
    throttleHandle()
    throttleHandle()
// 定时器,第一次触发不会立即执行,但是最后一次会延迟
    function throttle(fn, interval) {
      let timer = null
      return function () {
        let context = this
        let agrs = arguments
        if (!timer) {
          timer = setTimeout(function () {
            fn.apply(context, agrs)
            timer = null
          }, interval)
        }
      }
    }
    function handle() {
      console.log(Math.random());
    }
    const throttleHandle = throttle(handle, 1000)
    throttleHandle()
    throttleHandle()
    throttleHandle()
    throttleHandle()
    throttleHandle()
// 定时器+时间戳,第一次触发不会立即执行,最后一次也不会延迟
    function throttle(fn, delay) {
      let timer = null
      let startTime = Date.now()
      return function () {
        let curTime = Date.now()
        //curTime - startTime本次执行和上次执行的时间差
        //delay - (curTime - startTime)是否到达设定时间
        let remainning = delay - (curTime - startTime)
        let context = this
        let args = arguments
        clearInterval(timer)
        if (remainning <= 0) {
          fn.apply(context, agrs)
          startTime = Date.now()
        } else {
          timer = setTimeout(fn, remainning)
        }
      }
    }
    function handle() {
      console.log(Math.random());
    }
    const throttleHandle = throttle(handle, 1000)
    throttleHandle()
    throttleHandle()
    throttleHandle()
    throttleHandle()
    throttleHandle()

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值