CS Fundamentals Trainer · JavaScript · Performance & Memory

Predict the output: a leading-edge throttle with a 100 ms window.

let now = 0;
function throttle(fn, ms) {
  let last = -Infinity;
  return (arg) => {
    if (now - last >= ms) { last = now; fn(arg); }
  };
}
const onScroll = throttle((y) => console.log(`handle y=${y} at ${now}`), 100);
for (const [t, y] of [[0, 0], [30, 40], [90, 120], [100, 150], [180, 260], [210, 300]]) {
  now = t;
  onScroll(y);
}

Difficulty: medium

Answer this question

Related questions