JS 函数节流 && 防抖

节流

节流是将多次执行变成每隔一段时间执行。

场景: 在监听页面滚动的时候滚轮滚动一下会连续执行n多次回调函数,这样造成性能的损耗, 使用节流能够非常好的节省性能的损耗。
eg:
未使用节流 window.onscroll = function(){ console.log("scrolling")};


1_no.png

//鼠标滚一下,连续触发了13次。。

使用节流函数 window.onscroll = throttle(function(){ console.log("scrolling")}, 100);


JS 函数节流 && 防抖_第1张图片
1_yes.png

//鼠标滚一下,只触发了一次

节流函数的简单实现

function throttle(fn, delay){
  if(typeof fn !== "function"){
    return new Error("argument[0] is not a function")
  }
  let context = this;
  let timer = null;
  return function(...args){
    if(!timer){
      timer = setTimeout(() => {
        fn.apply(context, args);
        timer = null;
      }, delay)
    }
  }
}

防抖

防抖是将连续触发改变为直到最后一次且等待时间超过设定时间在执行,期间都会重新计时;

场景: 在输入input输入联想的时候,不使用防抖则会不停的发送ajax请求,造成资源浪费。

防抖简单实现

function debounce(fn, delay) {
    if(typeof fn !== "function"){
        return new Error("argument[0] is not a function");
    }
    let context = this;
    let now = Date.now();
    let timer = null;
    return function(...args){
        let remain = Date.now() - now;
        //如果连续操作时间小于delay的时间则清空定时器,继续重新设定
        if(remain < delay){
            clearTimeout(timer);
            timer = null;
            now = Date.now();
            timer = setTimeout(() => {
                fn.apply(context, args);
            }, delay)
        }
    }
}

//完整代码


    
    
        
    
    防抖


    
      
  

你可能感兴趣的:(JS 函数节流 && 防抖)