All files function.js

0% Statements 0/25
0% Branches 0/9
0% Functions 0/7
0% Lines 0/22

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39                                                                             
export function debounce(func, wait = 0) {
  wait = Math.round(wait, 10);
 
  let timerId;
  return function debounced(...args) {
    if (timerId) clearTimeout(timerId);
    timerId = setTimeout(() => {
      func.apply(this, args);
    }, wait);
  };
}
 
export function throttle(func, time) {
  let args;
  let timer = null;
  let lastTriggerTime = 0; // 首次触发执行
  function self(...a) {
    args = a;
    const ct = Date.now();
    const diff = ct - lastTriggerTime;
    if (timer) clearTimeout(timer);
 
    if (diff > time) {
      func.apply(this, args);
      lastTriggerTime = ct;
      return;
    }
    timer = setTimeout(() => {
      lastTriggerTime = Date.now();
      func.apply(this, args);
      timer = null;
    }, time - diff);
  }
  self.clear = () => {
    if (timer) clearTimeout(timer);
  };
  return self;
}