防抖和节流

189 阅读1分钟

防抖

用户触发事件过于频繁,只要最后一次操作的结果

原理:利用定时器

let ipt = document.querySelector('input')

    ipt.oninput = debounce(function () {
       console.log('事件触发了')  //这里如果使用this,指向的是window,因为此时的function在定时器中被调用
     }, 500)
     function debounce(fn, delay) {
       let t = null
       //return的是内部函数,使用了外部函数的变量(闭包)
       return function () {
         if (t != null) {
           clearTimeout(t)
         }
         t = setTimeout(() => {
           fn()   //改变this指向写为fn.call(this)
         }, delay)
       }
     }`


参考:[](https://www.bilibili.com/video/BV1ig411u7LG/?spm_id_from=autoNext)

节流

控制高频事件执行的次数

window.onscroll = throttle(function () {
        console.log('事件触发了') //这里如果使用this,指向的是window,因为此时的function在定时器中被调用
      }, 500)
      function throttle(fn, delay) {
        //return的是内部函数,使用了外部函数的变量(闭包)
        let flag = true
        return function () {
          if (flag) {
            setTimeout(() => {
              fn.call(this)
              flag = true
            }, delay)
          }
          flag = false
        }
      }