函数-防抖和节流

<!--
 * @Description: 
 * @Version: 1.0
 * @Autor: Helx
 * @Date: 2021-05-16 22:52:23
 * @LastEditors: Helx
 * @LastEditTime: 2021-11-18 19:19:13
-->
<!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>input防抖btn节流</title>
</head>

<body>
  <div style="display:flex">
    检索(防抖):<input id="inpt" type="type" />
    点击(节流):<button id="btn">点我</button>
  </div>
</body>
<script>
/* 为什么防抖和节流?
我们使用窗口的 resize,scorll,mousemove,mousehover;输入框等校验时,如果事件处理函数调用无限制,会加剧浏览器的负担,
尤其是执行了操作 DOM 的函数,那不仅造成计算资源的浪费,还会降低程序运行速度,甚至造成浏览的奔溃,影响用户体验。*/
  //防抖:一段时间没触发事件,处理函数才执行,当再次触发事件,就重新开始计时
  const debounce = function (fun, wait) {
    let timer = null;
    return function (args, t) {
      if (timer) clearTimeout(timer);
      timer = setTimeout(function () {
        fun(args, t);
      }, wait);
    }
  }
  //处理函数
  const changeInput = (args, t) => {
    console.log('args:', args, 't:', t);
  }
  const t1 = 1000;
  const _debounce = debounce(changeInput, t1);
  document.getElementById('inpt').oninput = function (e) {
    const val = e.target.value;
    _debounce(val, '输入框')
  }

  // 节流:当时间持续发生时,保证在一定时间段内只会处理一次事件函数
  const throttle = function (fun, wait) {
    let flag = false;
    return function (arg, t) {
      if (flag) return;
      flag = true
      setTimeout(function () {
        fun(arg, t);
        flag = false;
      }, wait)
    }
  }
  //处理函数
  const onClick = args => {
    console.log('args', args);
  }
  const t2 = 3000;
  const _throttle = throttle(onClick, t2); //三秒钟内只能触发一次
  document.getElementById('btn').onclick = function () {
    console.log('11111');// 多次打印
    _throttle('按钮触发');
  }
</script>

</html>

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值