lewenweijia / notes

🏊 dive dive diving
1 stars 0 forks source link

简易实现: 节流(throttle)和防抖 (debounce) #6

Open lewenweijia opened 4 years ago

lewenweijia commented 4 years ago
## 节流
function throttle(fn, interval) {
  let processing = false;

  return function (...args) {
    const context = this;

    if (!processing) {
      fn.apply(context, args);
      processing = true;

      setTimeout(() => {
    processing = false;
      }, interval);
    }
  }
}
lewenweijia commented 4 years ago
## 防抖
function debounce(fn, time) {
  let timeId;
  return function (...args) {
    const context = this;

    clearTimeout(timeId);
    timeId = setTimeout(() => {
      timeId = null;
      fn.apply(context, args)
    }, time);
  }
}