手撕JS——节流throttle

目录

时间戳实现

定时器实现

结合版

应用 


节流(throttle):不管事件触发频率多高,只在单位时间内执行一次。

既该事件不会重复触发,与防抖最大的区别,单位时间内触发就取消,防抖是以后一个为准

有两种方式可以实现节流,使用时间戳和定时器。

时间戳实现

第一次事件肯定触发,最后一次不会触发

    function throttle(event, time) {
      let pre = 0;
      return function (...args) {
        if (Date.now() - pre > time) {
          pre = Date.now();
          event.apply(this, args);
        }
      }

定时器实现

第一次事件不会触发,最后一次一定触发

    function throttle(event, time) {
      let timer = null;
      return function (...args) {
        if (!timer) {
          timer = setTimeout(() => {
            timer = null;
            event.apply(this, args);
          }, time);
        }
      }
    }

结合版

定时器和时间戳的结合版,也相当于节流和防抖的结合版,第一次和最后一次都会触发

    function throttle(event, time) {
      let pre = 0;
      let timer = null;
      return function (...args) {
        if (Date.now() - pre > time) {
          clearTimeout(timer);
          timer = null;
          pre = Date.now();
          event.apply(this, args);
        } else if (!timer) {
          timer = setTimeout(() => {
            event.apply(this, args);
          }, time);
        }
      }
    }

应用 

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>throttle</title>
</head>
<body>
  <script>
    function coloring(){
      let r=Math.floor(Math.random()*255);
      let g=Math.floor(Math.random()*255);
      let b=Math.floor(Math.random()*255);
      document.body.style.background=`rgb(${r},${g},${b})`
    }
    //定时器版
    function throttle(fn, delay) {
      let timer
      return function (...args) {
        if(!timer){
          timer=setTimeout(()=>{
            timer=null
            fn.apply(this, args)
          }, delay)
        } 
      }
    }
    //时间戳版
    function throttle2(fn,delay){
      let pre=0
      return function(...args){
        if(Date.now()-pre > delay){
          timer=setTimeout(()=>{
            pre=Date.now()
            fn.apply(this, args)
          })
        }
      }
    }
   window.addEventListener("resize",throttle2(coloring,1000))
  </script>
</body>
</html>

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值