手写防抖和节流

防抖: 在输入框中,可以使用防抖

  //手写防抖
  function debounce(fn, delay = 500) {
    let timer = null
    return function() {
      if(timer) {
        clearTimeout(timer)
      }
      timer = setTimeout(() => {
        fn.apply(this, arguments)
        timer = null
      },delay)
    }
  }
  const input1 = document.getElementById('input1')
  input1.addEventListener('keyup',debounce(function() {
    console.log(input1.value)
  }),500)

节流: 在拖拽中,可以使用节流,让它定时打印坐标

  function throttle(fun, delay=100) {
    let timer1 = null
    return function() {
      if(timer1) {
        return
      }
      timer1 = setTimeout(() => {
        fun.apply(this, arguments)
        timer1 = null
      }, delay)
    }
  }
posted @ 2021-04-11 21:57  嘿!那个姑娘  阅读(178)  评论(0编辑  收藏  举报