节流实现案例

本文介绍了一个使用JavaScript实现的节流函数案例,通过限制鼠标移动事件的触发频率,确保UI响应平滑。核心在于throttle函数,它在500毫秒内仅执行一次回调,有效防止了频繁事件导致的性能问题。
摘要由CSDN通过智能技术生成

节流案例

<!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>Document</title>
    <style>
      .box {
        width: 500px;
        height: 500px;
        background-color: #ccc;
        color: #fff;
        text-align: center;
        font-size: 100px;
      }
    </style>
  </head>
  <body>
    <div class="box"></div>

    <script>
      const box = document.querySelector('.box')
      let i = 1

      // 鼠标移动函数
      function mouseMove() {
        box.innerHTML = ++i
      }

      // 节流函数
      function thottle(fn, t) {
        // 起始时间
        let startTime = 0
        return function () {
          // 得到现在的时间
          let now = Date.now()
          // 判断大于等于500  调用函数
          if (now - startTime >= t) {
            fn()
            // 执行完成后将现在的时间赋值给起始时间
            startTime = now
          }
        }
      }
      box.addEventListener('mousemove', thottle(mouseMove, 500))
    </script>
  </body>
</html>

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值