防抖/节流

119 阅读1分钟
  • 函数防抖(debounce):当持续触发事件时,一定时间段内没有再触发事件,事件处理函数才会执行一次,如果设定的时间到来之前,又一次触发了事件,就重新开始延时
<!--防抖-->
function debounce(func, delay) {
  let timer = null;
  return function (...args) {
    if (timer) clearTimeout(timer);
    timer = setTimeout(() => {
      func.apply(this, args)
    }, delay)
  }
}
function showTop() {
    var scrollTop = document.body.scrollTop || document.documentElement.scrollTop;
    console.log('滚动条位置:' + scrollTop);
}
window.onscroll = debounce(showTop, 1000)
  • 节流函数(throttle):当持续触发事件时,保证一定时间段内只调用一次事件处理函数。
<!--节流-->
function throttle(func, delay) {
    var timer = null;
    return function (...arg) {
        if (!timer) {
            timer = setTimeout(function () {
                func.apply(this, arg);
                timer = null;
            }, delay);
        }
    }
}
function showTop() {
    var scrollTop = document.body.scrollTop || document.documentElement.scrollTop;
    console.log('滚动条位置:' + scrollTop);
}
window.onscroll = debounce(showTop, 1000)