面试官必问的函数节流和防抖

323 阅读1分钟

哈喽,大家好!我是奶茶不加糖。一个喜欢喝奶茶的前端攻城狮
( 哈哈,放一张新老公的照片(* ̄︶ ̄) )

前言

函数节流和函数防抖,两者都是优化高频率执行js代码的一种手段。

防抖函数

将多次触发变成最后一次触发

** 函数防抖的应用场景** :按钮多次重复点击避免重复请求后台数据,可以进行防抖函数,在一定时间内,按照最后一次计算

function debounce(fn,wait){
  let timer = null;
  return function (){
    let arg = arguments;
    if(timer){
      clearTimeout(timer);
      timer = null;
    }
    timer = setTimeout(()=>{
       fn.apply(this,arg)
    },wait)
  }
}
function clg(){
  console.log('clg')
}
window.addEventListener('resize',debounce(clg,1000))

节流函数

将多次执行变成每隔一个时间节点去执行的函数

** 函数节流的应用场景** :多数在监听页面元素滚动事件的时候会用到。因为滚动事件,是一个高频触发的事件

function throttle(fn,time){
  let lastTime = null;
  return function(){
    let nowTime = Date.now();
    if(nowTime - lastTime > time || !lastTime){
      fn();
      last = nowTime
    }
  }
}
function sayHi(){
  console.log('hi')
}
setInterval(throttle(sayHi,1000),500)