什么防抖和节流?JS实现代码与应用场景

76 阅读1分钟

什么是防抖?什么是节流?

防抖(debounce)

n秒后执行该函数,若重复触发则重置计时,保证在n秒内只执行一次。

debounce01.gif

应用场景:

读取用户输入发起http请求,一般用户输入中的字符不完整,输入完成或者停顿足够长时间才有效。

JS实现代码

function debounce(fun, delay) {
  const that = this;
  return function(args) {
    if (fun.id) clearTimeout(fun.id)
    fun.id = setTimeout(() => {
      fun.call(that, args)
    }, delay)
  }
}
// 要执行的函数
function setData(val) {
  inpVal1.value = val
}
// <input @input="onInput" />
function onInput(val) {
  const deFun = debounce(setData, 1000);
  deFun(val);
}

节流(throttle)

n秒内只执行一次,若重复尝试不生效。类似技能CD中(有的场景可以重新计算CD时间作为惩罚)。

throttle01.gif

应用场景:

抢红包/票、提交按钮、释放角色技能等等。

JS实现代码

function throttle(fun, wait) {
  const that = this;
  return function(args) {
    let now = Date.now();
    if (!fun.prev || now - fun.prev > wait) {
      fun.call(that, args);
      fun.prev = now;
    }
  }
}
// <button @click="onClick">点击计数{{ count }}</button>
function onClick(val) {
  count.value++;
  const throFun = throttle2(setData2, 1000);
  throFun(val)
}