Hi FE !
Ai
git
前端面试题
前端小tip
  • vite
  • webpack
npm
  • vue2
  • vue3
react
GitHub
Ai
git
前端面试题
前端小tip
  • vite
  • webpack
npm
  • vue2
  • vue3
react
GitHub
  • s008-手写函数节流★★

s008-手写函数节流★★

//手写函数节流,

function throttle(fn,delay = 100) {
  let timer = null;

  return function() {
    let ctx = this;
    if(timer) {
      return
    }
      timer = setTimeout(() => {
          fn.apply(ctx,arguments)
          timer = null;
      },delay)
  }
}

函数节流使用的挺多场景就是,拖拽

div1.addEventListener('drag',throttle(function(e) {
    console.log(e.offsetX)
},200))
function throttle(fn,delay) {
  let timer = null;
  let start = Date.now();
  return function() {
    let nowTime = Date.now();
    let left = delay - (nowTime - start);
    let context = this;
    let args = arguments;
    clearTimeout(timer);
    if(left <= 0) {
      fn.apply(context,agrs)
      start = Date.now();
    } else {
      timer = setTimeout(fn,left)
    }
  }
}



function throttle(fn, delay){
    let that = this
    let lastTime = 0
    return function() {
        let nowTime = new Date().getTime()
        if(nowTime - lastTime < delay) return // 两次时间间隔比设定的delay则return
        let arg = arguments // 此处为fn函数的参数
        fn.apply(that, arg)
        lastTime = nowTime // 把当前时间赋值给lastTime
    }
}



function test(a,b) {
    console.log(a,b)
}

let throttleTest = throttle(test, 1000)

window.onscroll = function(e) {
    throttleTest(1,2)
}
Edit this page
最近更新: 2025/6/27 02:24
Contributors: qdleader
qdleader
本站总访问量 129823次 | 本站访客数 12人