CS Fundamentals Trainer · JavaScript · Performance & Memory

Predict the output: a debounced search handler driven by a fake clock.

// A tiny fake clock so the timing is deterministic
let now = 0;
let timers = [];
const fakeSetTimeout = (fn, ms) => { const t = { fn, at: now + ms }; timers.push(t); return t; };
const fakeClearTimeout = (t) => { timers = timers.filter((x) => x !== t); };
const advanceTo = (time) => {
  timers.sort((a, b) => a.at - b.at);
  while (timers.length && timers[0].at <= time) { const t = timers.shift(); now = t.at; t.fn(); }
  now = time;
};

function debounce(fn, ms) {
  let t;
  return (arg) => { fakeClearTimeout(t); t = fakeSetTimeout(() => fn(arg), ms); };
}
const search = debounce((q) => console.log(`search "${q}" at ${now}`), 100);
search('j'); advanceTo(50);
search('ja'); advanceTo(120);
search('jav'); advanceTo(400);
search('java'); advanceTo(1000);

Difficulty: hard

Answer this question

Related questions