首页 > 其他 > 详细

防抖和节流

时间:2021-09-06 23:47:55      阅读:46      评论:0      收藏:0      [点我收藏+]
/**
 * 防抖
 *
 * @param {*} f
 * @param {*} wait
 * @return {*} 
 */
function debounce(f, wait) {
  let timer = null;
  return (...args) => {
    if(timer) {
      clearTimeout(timer)
    }
    timer = setTimeout(() => {
      f(...args);
    }, wait);
  }
}

/**
 * 节流 非首次执行
 *
 * @param {*} f
 * @param {*} wait
 * @return {*} 
 */
function throttle(f, wait) {
  let timer = null;
  return (...args) => {
    if(timer) {
      return
    }
    timer = setTimeout(() => {
      f(...args);
      timer = null;
    }, wait);
  }
}

/**
 * 节流 首次执行
 *
 * @param {*} f
 * @param {*} wait
 * @return {*} 
 */
function throttle(f, wait) {
  let last = 0;
  return (...args) => {
    const now = Date.now();
    if(now - last >= wait) {
      f(...args);
      last = now;
    }
  }
}

/**
 * 节流 两者结合
 *
 * @param {*} f
 * @param {*} wait
 * @return {*} 
 */
function throttle(f, wait) {
  let last = 0;
  let timer = null;
  return (...args) => {
    const now = Date.now();
    const remaining = wait - (now - last);

    clearTimeout(timer)

    if(remaining <= 0) {
      f(...args);
      last = Date.now();
    }
    else {
      if(timer) return;
      timer = setInterval(() => {
        f(...args);
        last = Date.now();
      }, remaining);

    }
  }
}

function sayHellow() {
  console.log(‘hellow‘);
}

// const debounceSayHellow = debounce(sayHellow, 2000);

// debounceSayHellow();
// debounceSayHellow();
// debounceSayHellow();
// debounceSayHellow();
// debounceSayHellow();
// debounceSayHellow();

const throttleSayHellow = throttle(sayHellow, 2000);

setInterval(() => {
  throttleSayHellow();
}, 500);

  

防抖和节流

原文:https://www.cnblogs.com/tipsydr/p/15233331.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!