防抖与节流

封装工具   2024-08-18 17:27   135   0  
防抖.
function debounce(fn, delay) {
  let timer = null
  const _debounce = function () {
    var _this = this;
    var args = arguments;
    if (timer) clearTimeout(timer)
    timer = setTimeout(() => {
      fn.apply(_this, args);
    }, delay)
  }
  return _debounce
}
ES6+
export const debounce = (fn, delay) => {
    let timer = null;
    let that = this;
    return (...args) => {
        timer && clearTimeout(timer)
        timer = setTimeout(() => {
            fn.apply(that, args);
        }, delay);
    }
节流.
function throttle(fn, delay) {
    var timer;
    return function () {
        var _this = this;
        var args = arguments;
        if (timer) {
            return;
        }
        timer = setTimeout(function () {
            fn.apply(_this, args);
            timer = null; 
        }, delay)
    }
}
ES6+
export const throttle = (fn, delay) => {
    let timer = null;
    let that = this;
    return (args) => {
        if (timer) return;
        timer = setTimeout(() => {
            fn().apply(that, args);
            timer = null;
        }, delay);
    }
}