JS优化,减少重复请求

1.前言

无聊点点公司的网页, 发现公司网站的一搜索请求是实时请求的,点开控制栏发现每输一个字符都会请求一次,虽然请求大小不大,但是这样不友好,为了减少请求次数,我给项目加了两个方法,分别是节流和防抖函数。

节流函数一般用于,类似按钮请求这些,防止你一秒点击多次按钮产生重复请求

防抖函数一般用于,类似实时监听input的请求,防止请求过多

2.代码

<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>Document</title>
</head>

<body>
  <input type="text" id="input">
  <div id="getVal">get</div>
  <script>
    //函数节流
    function throttle(fn, gapTime) {
      if (gapTime == null || gapTime == undefined) {
        gapTime = 1500
      }

      let _lastTime = null

      // 返回新的函数
      return function (e) {
        let _nowTime = +new Date()
        if (_nowTime - _lastTime > gapTime || !_lastTime) {
          console.log('on')
          fn.apply(this, arguments) //将this和参数传给原函数
          _lastTime = _nowTime
        }
      }
    }
    //防抖函数
    function debounce(handle, delay) {
      var timer = null;
      return function () {
        var _this = this,
          _arg = arguments;
        clearTimeout(timer);
        timer = setTimeout(function () {
          handle.apply(_this, _arg);
        }, delay);
      }
    } // 其中 handle 为需要进行防抖操作的函数,delay 为延迟时间

    var btn = document.getElementById("getVal");
    var input = document.getElementById("input");
    var kkk = "2222222"
    //防止连点请求过多,一秒内只请求一次
    btn.onclick = throttle(function () {
      console.log(input.value)

    }, 1000)


    //防止实时监听请求次数过多
    function ajax(a) {
      console.log(a);// 搜索框value值
      console.log(input.value);// 搜索框value值
    }
    input.oninput = debounce(function () {
      ajax(kkk)
    }, 500)




  </script>
</body>

</html>

猜你喜欢

转载自blog.csdn.net/CrazBarry/article/details/98207937