关于javascript:js的防抖和节流函数

防抖函数

能够用防抖debounce等优化形式,缩小http申请;

这里以滚动条事件举例:防抖函数 onscroll 完结时触发一次,提早执行

function debounce(fun,wait){
        let timeout
        return function(){
            let content = this
            let args = arguments
            if(timeout){
                clearTimeout(timeout)
            }
            timeout = setTimeout(()=>{
                fun.apply(content,args)
            },wait)
        }
    }

    window.onscroll = debounce(function(){
        console.log('我就执行一次')
    },5000)

节流函数

只容许一个函数在N秒内执行一次。滚动条调用接口时,能够用节流throttle等优化形式,缩小http申请;

function throttle(fn, delay) {
  let prevTime = Date.now();
  return function() {
    let curTime = Date.now();
    if (curTime - prevTime > delay) {
      fn.apply(this, arguments);
      prevTime = curTime;
    }
  };
}
// 应用
var throtteScroll = throttle(function() {
  console.log('我就执行一次')
}, 1000);
window.onscroll = throtteScroll;

评论

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

这个站点使用 Akismet 来减少垃圾评论。了解你的评论数据如何被处理