函数节流和函数防抖

152 阅读1分钟
  1. 函数节流
  • 规定时间内对第一次操作有效
  var oDiv = document.getElementById('div1')
        function throttle(fn,delay){
            var startTime = 0
            return function(){
                var nowTime = Date.now()
                if(nowTime -startTime > delay){
                    fn.call(this)//在这得调用一些串进来的的fn()
                    startTime = nowTime
                }
            }
        }
       
        document.onmousemove = throttle(function(){
        //    console.log(111)
           console.log(Date.now())
           console.log(this)
       },1000)
    //    当不改变指针时这个this指向的是window
    //    改变指针后指向的是document
  1. 函数防抖
  • 规定时间内只对最后一次操作有效
   <script>
        // 函数去抖动,只对最后一次生效
        var oBtn =document.getElementById('btn')
        function debounce(fn,delay){
            var timer = null
            return function(){
                clearTimeout(timer)
                timer = setTimeout(function(){
                    fn.apply(this)
                },delay)
            }
        }
        oBtn.onclick = debounce(function(){
            console.log(Date.now())
        },300)
    </script>