美文网首页
函数节流和防抖

函数节流和防抖

作者: DSuperLu | 来源:发表于2020-03-15 23:12 被阅读0次

事件节流和防抖利用setTimeout控制函数执行的时机,提高性能,解决高频触发问题。常见于onscroll、onresize,频繁点击button等。

函数节流(Throttle)

节流在一定时间内调用多次,总是执行第一次调用的,执行完成后,才能再次调用。

function throttle(func, wait) {
    let timer;
    return function() {
        let context = this;
        let args = arguments;
        if (!timer) {
            timer = setTimeout(() => {
                timeout = null;
                func.apply(context, args)
            }, wait)
        }
    }
}

函数防抖(Debounce)

防抖在一定时间内调用多次,后续的调用会覆盖前面的调用,执行的永远是最后一次调用的。

function debounce(func, delay) {
  let timer;
  return function() {
    clearTimeout(timer) // 如果持续触发,那么就清除定时器,定时器的回调就不会执行。
    timer = setTimeout(() => {
      func.apply(this, arguments)
    }, delay)
  }
}

相关文章

网友评论

      本文标题:函数节流和防抖

      本文链接:https://www.haomeiwen.com/subject/fjsiehtx.html