函数节流与防抖

2018-12-26  本文已影响0人  大脸猫_2e21
<!DOCTYPE html>
<html>

<head>
  <meta charset="UTF-8">
  <title>函数节流与防抖</title>
  <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
  <style type="text/css">
     
  </style>
</head>

<body>
  <input type="text">
  <div id="panel" style="background:red;width:200px;height:200px"></div>
  <script>
//函数防抖  是只有在函数有足够的空闲时间的时候 才会触发  节流是在一段时间内触发
    function debounce(func, delay){
      var timeout
      return function(e){
        console.log('清除', timeout, e.target.value)
        clearTimeout(timeout)
        var context = this, args = arguments
        console.log("新的", timeout, e.target.value)
        timeout = setTimeout(function(){
          console.log('---')
          console.log(context)
          func.apply(context, args)
        }, delay)
      }
    }

    var validate = debounce(function(e){
      console.log('change', e.target.value, new Date-0)
    }, 380)

    document.querySelector('input').addEventListener('input', validate)
    console.log(12)


    // 节流
    //节流的概念可以想想一下水坝,你建了水坝在河道中,不能让水流动不了,你只能让水流慢些。
    //你不能让用户的方法都不执行。如果这样干,就是debounce了。为了让用户的方法在某个时间段内只执行一次,我们需要保存上次执行的事件点与定时器
    
    function throttle(fn, threshhold){
      var timeout 
      var start = new Date
      var threshhold = threshhold || 160
      return function(){
        var context = this, args = arguments, curr = new Date() - 0
        clearTimeout(timeout)  //总是干掉时间回调
        if(curr - start >= threshhold){
          console.log('now', curr, curr - start) //注意这里相减的结果,都差不多是160左右
          fn.apply(context, args)  //只执行一部分方法,这些方法是在某个时间段内执行一次
          start = curr
        }else{
          //让方法在脱离事件后也能执行一次
          timeout = setTimeout(function(){
            fn.apply(context, args)
          }, threshhold)
        }
      }
    }

    var mousemove = throttle(function(e){
      console.log(e.pageX, e.pageY)
    })

    document.querySelector('#panel').addEventListener('mousemove', mousemove)

  </script>
</body>

</html>
上一篇 下一篇

猜你喜欢

热点阅读