js防抖和限流函数

function debounce(fn, delay) {
      let timer;
      let tht = this;
      return function (...args) {
        clearTimeout(timer)
        console.log(...args)
        timer = setTimeout(() => { fn.apply(tht, args) }, delay)
      }
    }
    function throttle(fn, delay) {
      let timer;
      let tht = this;
      return function (...args) {
        if (timer) { return; }
        timer = setTimeout(() => {
          fn.apply(tht, args)
          timer = null
        }, delay)
      }
    }
    let divDom = document.getElementsByTagName('div')[0]
    let test = function (...args) {
      console.log('000000000000000000' + args)
    }
    //let ff = debounce(test, 1000)
    let ff = throttle(test, 1000)
    //divDom.addEventListener('click', ff)//无参数这样调用
    divDom.addEventListener('click', function () { //有参数这样调用
      ff(4, 5)
    })

 

posted @ 2024-05-15 13:54  howhy  阅读(48)  评论(0编辑  收藏  举报