手写节流函数

58 阅读1分钟

一、手写节流函数

控制高频事件中业务逻辑代码的执行次数。每隔多久才执行一次

以滑动条滚动事件为例

// 利用闭包封装一个 throttle 函数
function throttle(fn,delay){
    let flag = true
    return function(){
        if(flag){
          setTimeout(()=>{
          // 执行传入的回调函数
              fn.call(this)
          // 执行完毕后将 flag设置为true
              falg = true
          },delay)
        }
        falg = false
    }
}
// 以滑动条滚动事件为例
window.addEventListener('scroll',throttle(function(){
    console.log('hello world!' )
},500)