JavaScript 防抖 & 节流

23 阅读1分钟

防抖

防抖:n秒后执行某事件函数,若n秒内重复触发该函数,则重新计时

  • 核心代码
function debounce(fun, delay){
  let timer = null
  return function(){
    let _this = this
    let args = arguments
    clearTimeout(timer)
    timer = setTimeout(() => {
      fun.apply(_this, args)
    }, delay);
  }
}
  • 示例
<input type="text" id="input">

// n秒后需要执行的事件函数
function fun(val){
  console.log(val);
}
// 调用防抖函数
var debounceFn = debounce(fun, 1000)
document.getElementById('input').addEventListener('keyup', e=>{
  debounceFn(e.target.value);
})

节流

节流:n秒后执行某事件函数,若n秒内多次触发该事件,只执行一次

  • 核心代码
function throttle(fun, delay) {
  let timer = null
  return function(){
    let _this = this
    let args = arguments
    if(!timer){
      timer = setTimeout(() => {
        fun.apply(_this, args)
        timer = null
      }, delay);
    }
  }
}
  • 示例
<button id="btn">提交</button>

function handle(){
  console.log('提交');
}
document.getElementById('btn').onclick =  throttle(handle, 1000)