防抖节流

发布时间 2023-11-26 01:27:08作者: adong搬砖

      //****************节流**********************
      //节流代码
      function throttle(f) {
        let timer
        return function () {
          if (timer) return
          timer = setTimeout(() => {
            f()
            timer=null
          }, 500)
        }
      }
      // //业务代码
      const fn = () => {
        console.log(1111111)
      }
      document.onmousemove = throttle(fn)
//****************防抖**********************
      const inp = document.querySelector('input')
      //防抖代码
      function debounce(f) {
        let timer
        return function () {
          clearTimeout(timer)
          timer = setTimeout(() => {
            f()
          }, 1000)
        }
      }
      //业务代码
      const fn = () => {
        console.log(1111111)
      }
      inp.oninput = debounce(fn)