节流和防抖

文章介绍了JavaScript中两种优化性能的技术——节流和防抖。节流通过限制函数在一定时间内的执行次数,防止过度频繁操作;防抖则是等待一段时间无新触发后才执行函数,避免资源浪费。示例代码分别展示了如何实现节流和防抖函数,并应用到按钮点击和输入框keyup事件中。
摘要由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>
  </head>
  <body>
    <button id="btn">点击</button>
  </body>
  <script>
    function thow(func, wait) {
      let timer
      return function () {
        if (!timer) {
          timer = setTimeout(() => {
            func()
            timer = null
          }, wait)
        }
      }
    }
    function handle() {
      console.log(Math.random())
    }
    document.getElementById('btn').onclick = thow(handle, 2000)
  </script>
</html>

防抖:触发事件后,等待一定时间(如1000毫秒)再执行函数,如果在等待时间内又触发了事件,则重新计时。

<!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>
  </head>
  <body>
    <input type="text" id="input" />
  </body>
  <script>
    const input = document.getElementById('input')
    function debounce(delay, calllback) {
      let timer
      return function (value) {
        clearTimeout(timer)
        timer = setTimeout(function () {
          calllback(value)
        }, delay)
      }
    }
    function fn(value) {
      console.log(value)
    }
    const debounces = debounce(1000, fn)
    input.addEventListener('keyup', function (e) {
      debounces(e.target.value)
    })
  </script>
</html>

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值