Debounce, Throttle and Memoization in JavaScript
Some events fire far more often than an app can or should react: every keystroke in a search box, every pixel of scrolling, every resize. Some calculations or API calls are repeated with the same input again and again. Three small techniques handle this: debounce waits until the events stop, throttle lets one call through per time window, and memoization remembers previous results. They appear in every front end and in many interview rounds, and they make tests flaky when testers do not understand them. In this lesson you will write all three from scratch and watch exactly when they fire using fake timers, which is also the way to test time-based code without real waiting.
📖 What You’ll Learn: why high-frequency events need control, debounce (trailing and leading), throttle, the difference between them with a timeline, cancel and flush, fake timers with node:test mock.timers, memoization and cache keys, memoizing async calls (deduplicating requests), when not to memoize, how these affect UI test stability, and how to test them.
🌊 The Problem: Too Many Events
Type “playwright” into a search box: that is 10 input events in about a second. Calling the search API for each one wastes 9 requests, and results may even arrive out of order. Scrolling can fire dozens of events per second. The solution is to control how often the expensive function runs.
| Technique | Runs the function | Typical use |
|---|---|---|
| Debounce | Once, after events have stopped for N ms | Search-as-you-type, auto-save, resize end, form validation |
| Throttle | At most once every N ms while events continue | Scroll and mouse-move handlers, progress updates, rate-limited APIs |
| Memoize | Once per distinct input, then returns the cached result | Expensive calculations, repeated API lookups |
To see exactly when things happen, the examples use Node.js’s built-in fake timers: mock.timers.enable() replaces setTimeout and Date with a clock that only moves when we call mock.timers.tick(ms). No real waiting, and the output is identical on every run. One catch, shown below: during a single big tick, the fake Date.now() jumps to the end of the tick before timers fire, so callbacks see the wrong time. The examples therefore use a small advance(ms) helper that ticks one millisecond at a time.
📄 fake-timers.mjs
import { mock } from "node:test";
mock.timers.enable({ apis: ["setTimeout", "Date"] }); // fake clock: time only moves when we say so
const advance = (ms) => { for (let i = 0; i < ms; i++) mock.timers.tick(1); }; // 1 ms steps keep Date.now() exact
const at = () => `t=${Date.now()}ms`;
setTimeout(() => console.log("timer A should fire at t=300 -> Date says", at()), 300);
mock.timers.tick(1000); // one big jump
mock.timers.reset();
mock.timers.enable({ apis: ["setTimeout", "Date"] });
setTimeout(() => console.log("timer B should fire at t=300 -> Date says", at()), 300);
advance(1000); // 1 ms steps: Date.now() is exact
console.log("end", at());
⌨️ Terminal
node fake-timers.mjs
🖥️ Output
timer A should fire at t=300 -> Date says t=1000ms
timer B should fire at t=300 -> Date says t=300ms
end t=1000ms
⏸️ Debounce
Definition: a debounced function delays running until it has not been called for wait ms. Every new call restarts the timer, so a burst of calls produces one run, with the latest arguments, after the burst ends:
📄 debounce.mjs
import { mock } from "node:test";
mock.timers.enable({ apis: ["setTimeout", "Date"] }); // fake clock: time only moves when we say so
const advance = (ms) => { for (let i = 0; i < ms; i++) mock.timers.tick(1); }; // 1 ms steps keep Date.now() exact
const at = () => `t=${Date.now()}ms`;
function debounce(fn, wait) {
let timer;
return (...args) => {
clearTimeout(timer); // cancel the previous pending call
timer = setTimeout(() => fn(...args), wait);
};
}
const search = debounce((term) => console.log(`${at()} SEARCH "${term}"`), 300);
// the user types "qa", pauses, then types " tools" quickly
for (const [delay, text] of [[0, "q"], [100, "qa"], [600, "qa "], [80, "qa t"], [90, "qa to"], [70, "qa too"], [60, "qa tool"], [50, "qa tools"]]) {
advance(delay);
console.log(`${at()} typed "${text}"`);
search(text);
}
advance(1000);
⌨️ Terminal
node debounce.mjs
🖥️ Output
t=0ms typed "q"
t=100ms typed "qa"
t=400ms SEARCH "qa"
t=700ms typed "qa "
t=780ms typed "qa t"
t=870ms typed "qa to"
t=940ms typed "qa too"
t=1000ms typed "qa tool"
t=1050ms typed "qa tools"
t=1350ms SEARCH "qa tools"
Eight keystrokes, two searches: one after the pause in typing, one after the user finished. Each search ran 300 ms after the last keystroke of its burst.
Leading edge, cancel and flush
Sometimes you want the first call to run immediately and ignore the rest of the burst (a “Submit” button that must not submit twice). That is a leading debounce. Production versions also offer cancel() (drop the pending call, for example when a component unmounts) and flush() (run it now, for example before navigating away):
📄 debounce-options.mjs
import { mock } from "node:test";
mock.timers.enable({ apis: ["setTimeout", "Date"] }); // fake clock: time only moves when we say so
const advance = (ms) => { for (let i = 0; i < ms; i++) mock.timers.tick(1); }; // 1 ms steps keep Date.now() exact
const at = () => `t=${Date.now()}ms`;
function debounce(fn, wait, { leading = false } = {}) {
let timer = null;
let lastArgs = null;
const debounced = (...args) => {
const callNow = leading && timer === null;
clearTimeout(timer);
lastArgs = args;
timer = setTimeout(() => {
timer = null;
if (!leading) fn(...lastArgs);
}, wait);
if (callNow) fn(...args);
};
debounced.cancel = () => { clearTimeout(timer); timer = null; };
debounced.flush = () => { if (timer !== null) { debounced.cancel(); fn(...lastArgs); } };
return debounced;
}
const submit = debounce((id) => console.log(`${at()} submit order ${id}`), 500, { leading: true });
submit(1); advance(100); submit(1); advance(100); submit(1); // triple click
advance(1000);
submit(2); // later click works again
const save = debounce((text) => console.log(`${at()} auto-save "${text}"`), 1000);
save("draft 1"); advance(200); save("draft 2");
save.flush(); // user closes the editor: save immediately
save("draft 3"); save.cancel(); // discarded
advance(2000);
console.log("end", at());
⌨️ Terminal
node debounce-options.mjs
🖥️ Output
t=0ms submit order 1
t=1200ms submit order 2
t=1400ms auto-save "draft 2"
end t=3400ms
🚿 Throttle
Definition: a throttled function runs at most once per interval ms. Unlike debounce, it keeps running regularly while events continue, which is what you want for scroll positions or progress bars:
📄 throttle.mjs
import { mock } from "node:test";
mock.timers.enable({ apis: ["setTimeout", "Date"] }); // fake clock: time only moves when we say so
const advance = (ms) => { for (let i = 0; i < ms; i++) mock.timers.tick(1); }; // 1 ms steps keep Date.now() exact
const at = () => `t=${Date.now()}ms`;
function throttle(fn, interval) {
let last = -Infinity;
let timer = null;
let pendingArgs = null;
return (...args) => {
const now = Date.now();
const remaining = interval - (now - last);
if (remaining <= 0) { // window has passed: run now
last = now;
fn(...args);
} else { // inside the window: remember the latest call for the end
pendingArgs = args;
timer ??= setTimeout(() => {
last = Date.now();
timer = null;
fn(...pendingArgs);
}, remaining);
}
};
}
const onScroll = throttle((y) => console.log(`${at()} update header at scrollY=${y}`), 200);
// a scroll event every 50 ms for 600 ms
for (let y = 0; y <= 600; y += 50) {
onScroll(y * 2);
advance(50);
}
advance(500);
⌨️ Terminal
node throttle.mjs
🖥️ Output
t=0ms update header at scrollY=0
t=200ms update header at scrollY=300
t=400ms update header at scrollY=700
t=600ms update header at scrollY=1100
t=800ms update header at scrollY=1200
13 scroll events, 5 updates: one immediately, one per 200 ms window while scrolling continues, and a final “trailing” call at t=800 so the header shows the last position (1200) instead of a stale one.
⚖️ Debounce vs Throttle on the Same Events
The clearest way to remember the difference is to feed identical events to both:
📄 compare.mjs
import { mock } from "node:test";
mock.timers.enable({ apis: ["setTimeout", "Date"] }); // fake clock: time only moves when we say so
const advance = (ms) => { for (let i = 0; i < ms; i++) mock.timers.tick(1); }; // 1 ms steps keep Date.now() exact
const at = () => `t=${Date.now()}ms`;
function debounce(fn, wait) {
let t;
return (...a) => { clearTimeout(t); t = setTimeout(() => fn(...a), wait); };
}
function throttle(fn, interval) {
let last = -Infinity;
return (...a) => { const now = Date.now(); if (now - last >= interval) { last = now; fn(...a); } };
}
const runs = { debounce: [], throttle: [] };
const d = debounce((i) => runs.debounce.push(`#${i}@${Date.now()}`), 250);
const th = throttle((i) => runs.throttle.push(`#${i}@${Date.now()}`), 250);
// 20 events, one every 50 ms (1 second of continuous activity)
for (let i = 1; i <= 20; i++) { d(i); th(i); advance(50); }
advance(1000);
console.log("events: 20");
console.log("debounce:", runs.debounce.length, runs.debounce);
console.log("throttle:", runs.throttle.length, runs.throttle);
⌨️ Terminal
node compare.mjs
🖥️ Output
events: 20
debounce: 1 [ '#20@1200' ]
throttle: 4 [ '#1@0', '#6@250', '#11@500', '#16@750' ]
- Debounce ran once, after the activity stopped, with the last event.
- Throttle ran regularly during the activity (this simple version has no trailing call, so the last few events were dropped).
- Libraries such as lodash provide well-tested
debounceandthrottlewith leading, trailing and maxWait options.
🧠 Memoization
Definition: memoization caches a function’s results by its arguments, so repeated calls with the same input return instantly instead of recomputing. It is only safe for pure functions (same input, same output, no side effects):
📄 memoize.js
function memoize(fn, keyFn = (...args) => JSON.stringify(args)) {
const cache = new Map();
const memo = (...args) => {
const key = keyFn(...args);
if (cache.has(key)) { memo.hits++; return cache.get(key); }
memo.misses++;
const result = fn(...args);
cache.set(key, result);
return result;
};
memo.hits = 0;
memo.misses = 0;
memo.clear = () => cache.clear();
return memo;
}
// classic example: naive Fibonacci makes an exponential number of calls
let naiveCalls = 0;
const fibNaive = (n) => { naiveCalls++; return n < 2 ? n : fibNaive(n - 1) + fibNaive(n - 2); };
console.log("naive fib(25) =", fibNaive(25), "calls:", naiveCalls.toLocaleString("en-IN"));
const fib = memoize((n) => (n < 2 ? n : fib(n - 1) + fib(n - 2)));
console.log("memo fib(25) =", fib(25), "computed:", fib.misses, "cache hits:", fib.hits);
console.log("memo fib(70) =", fib(70), "computed:", fib.misses); // fib(80+) exceeds Number.MAX_SAFE_INTEGER
// cache keys: objects need a key function (JSON by default)
const discount = memoize((cart) => cart.items.reduce((s, p) => s + p, 0) * 0.1);
discount({ items: [100, 200] });
discount({ items: [100, 200] }); // a different object, same content -> cache hit
console.log("discount hits:", discount.hits);
⌨️ Terminal
node memoize.js
🖥️ Output
naive fib(25) = 75025 calls: 2,42,785
memo fib(25) = 75025 computed: 26 cache hits: 23
memo fib(70) = 190392490709135 computed: 71
discount hits: 1
⚠️ Watch out: Do not memoize functions that depend on time, randomness or external state (the current user, the database, Date.now()): they would return stale results. And an unbounded cache is a memory leak (see the performance lesson): limit its size or let entries expire.
Memoizing async calls: deduplicate requests
Caching the promise instead of the result means simultaneous callers share one request. This is how data libraries avoid fetching the same user five times when five components ask at once:
📄 memo-async.mjs
let requests = 0;
async function fetchUser(id) {
requests++;
await new Promise((r) => setTimeout(r, 50)); // pretend network
return { id, name: `User ${id}` };
}
const inFlight = new Map();
function getUserOnce(id) {
if (!inFlight.has(id)) {
const p = fetchUser(id).catch((e) => { inFlight.delete(id); throw e; }); // do not cache failures
inFlight.set(id, p);
}
return inFlight.get(id);
}
const users = await Promise.all([getUserOnce(7), getUserOnce(7), getUserOnce(8), getUserOnce(7)]);
console.log(users.map((u) => u.name), "network requests:", requests);
⌨️ Terminal
node memo-async.mjs
🖥️ Output
[ 'User 7', 'User 7', 'User 8', 'User 7' ] network requests: 2
🧪 Tester Scenario: Testing Debounced Code Reliably
A UI test that types into a debounced search and immediately checks the results fails, or passes only sometimes. Two fixes: in UI tests, wait for the outcome (a web-first assertion or the network response), never a fixed sleep; in unit tests, control the clock with fake timers. Here is a real unit test with the Node.js test runner (covered in Module 14):
📄 debounce.test.mjs
import { test, mock } from "node:test";
import assert from "node:assert/strict";
function debounce(fn, wait) {
let t;
return (...a) => { clearTimeout(t); t = setTimeout(() => fn(...a), wait); };
}
test("debounced search calls the API once with the final term", () => {
mock.timers.enable({ apis: ["setTimeout"] });
const api = mock.fn();
const search = debounce(api, 300);
for (const term of ["p", "pl", "pla", "play"]) { search(term); mock.timers.tick(100); }
assert.equal(api.mock.callCount(), 0, "no call while typing");
mock.timers.tick(300);
assert.equal(api.mock.callCount(), 1);
assert.deepEqual(api.mock.calls[0].arguments, ["play"]);
mock.timers.reset();
});
test("a pause between words triggers two searches", () => {
mock.timers.enable({ apis: ["setTimeout"] });
const api = mock.fn();
const search = debounce(api, 300);
search("qa"); mock.timers.tick(500);
search("qa tools"); mock.timers.tick(500);
assert.deepEqual(api.mock.calls.map((c) => c.arguments[0]), ["qa", "qa tools"]);
mock.timers.reset();
});
⌨️ Terminal
node --test debounce.test.mjs
🖥️ Output
✔ debounced search calls the API once with the final term (2.0853ms)
✔ a pause between words triggers two searches (0.2546ms)
ℹ tests 2
ℹ suites 0
ℹ pass 2
ℹ fail 0
ℹ cancelled 0
ℹ skipped 0
ℹ todo 0
ℹ duration_ms 10.0126
Both tests finished instantly although they simulate more than a second of typing. In Playwright, page.clock gives the same control over time inside the browser (await page.clock.install(), then await page.clock.runFor(300)).
📝 Practice Questions with Answers
Try each question on your own first, then open the answer to check your work. Run the code with node practice.js.
Q1. Write debounce(fn, wait) and show that 5 rapid calls (10 ms apart) produce one call, using fake timers.
Show answer
📄 practice1.mjs
import { mock } from "node:test";
mock.timers.enable({ apis: ["setTimeout", "Date"] }); // fake clock: time only moves when we say so
const advance = (ms) => { for (let i = 0; i < ms; i++) mock.timers.tick(1); }; // 1 ms steps keep Date.now() exact
const at = () => `t=${Date.now()}ms`;
const debounce = (fn, wait) => { let t; return (...a) => { clearTimeout(t); t = setTimeout(() => fn(...a), wait); }; };
const log = debounce((n) => console.log(`${at()} called with ${n}`), 100);
for (let i = 1; i <= 5; i++) { log(i); advance(10); }
advance(200);🖥️ Output
t=140ms called with 5Q2. Write a simple throttle(fn, ms) (no trailing call) and show how many of 10 calls, 30 ms apart, get through with ms = 100.
Show answer
📄 practice2.mjs
import { mock } from "node:test";
mock.timers.enable({ apis: ["setTimeout", "Date"] }); // fake clock: time only moves when we say so
const advance = (ms) => { for (let i = 0; i < ms; i++) mock.timers.tick(1); }; // 1 ms steps keep Date.now() exact
const at = () => `t=${Date.now()}ms`;
const throttle = (fn, ms) => { let last = -Infinity; return (...a) => { if (Date.now() - last >= ms) { last = Date.now(); fn(...a); } }; };
const ran = [];
const t = throttle((i) => ran.push(i), 100);
for (let i = 1; i <= 10; i++) { t(i); advance(30); }
console.log(ran.length, ran);🖥️ Output
3 [ 1, 5, 9 ]Q3. Memoize a slow square(n) and show that the second call with the same input is a cache hit.
Show answer
📄 practice3.js
let computed = 0;
const cache = new Map();
const square = (n) => {
if (cache.has(n)) return cache.get(n);
computed++;
cache.set(n, n * n);
return n * n;
};
console.log(square(12), square(12), square(5), "computed:", computed);🖥️ Output
144 144 25 computed: 2Q4. Which technique would you use for: (a) saving a form 2 seconds after the user stops typing, (b) updating a “scroll to top” button while scrolling, (c) a currency conversion rate looked up many times per page?
Show answer
(a) Debounce, (b) throttle, (c) memoize (with an expiry, because rates change over time).
Q5. Why is memoizing this function a bug?
const getGreeting = memoize((name) => `Good ${new Date().getHours() < 12 ? "morning" : "evening"}, ${name}`);Show answer
The result depends on the current time, which is not part of the cache key, so after the first call it keeps returning “Good morning” all day. Only memoize pure functions, or include every input (here the hour) in the key.
Q6. A Playwright test types into a debounced search and checks await page.locator(".result").count() immediately. It fails randomly. How do you fix it?
Show answer
Replace the immediate count with a retrying assertion: await expect(page.locator(".result")).toHaveCount(3), or wait for the search response with page.waitForResponse("**/api/search*") started before typing. For precise control use page.clock to fast-forward past the debounce delay. Never add a fixed waitForTimeout.
🧠 MCQ Quiz: Debounce, Throttle, Memoize
10 questions on this lesson. Pick one answer for each, then press Check answers to see your score and an explanation for every question.
- What does debounce do?Answer: Runs the function once after calls stop for N ms. Every new call restarts the timer.
- What does throttle do?Answer: Runs the function at most once per time window. It keeps firing regularly during activity.
- Which is better for search-as-you-type?Answer: Debounce. Search when the user pauses.
- Which is better for updating something during scrolling?Answer: Throttle. Regular updates while scrolling continues.
- What does a leading-edge debounce do?Answer: Runs on the first call and ignores the rest of the burst. Useful against double submits.
- Which functions are safe to memoize?Answer: Pure functions. Same input must always give the same output.
- Why cache the promise when memoizing an async call?Answer: Simultaneous callers share one request. Remove failed promises from the cache.
- What do fake timers let a test do?Answer: Advance time instantly and deterministically. node:test mock.timers, Playwright page.clock.
- What is the risk of an unbounded memoization cache?Answer: A memory leak. Limit size or expire entries.
- A debounced search test fails randomly. What is the best fix?Answer: Use an assertion that waits for the result. Wait for the outcome, not for a fixed time.
💼 Interview Questions and Answers
Q1. Explain the difference between debounce and throttle with an example.
Both limit how often a function runs during a burst of events. Debounce waits for a quiet period: typing “playwright” fires 10 input events but the search runs once, 300 ms after the last keystroke. Throttle guarantees a maximum rate: while scrolling for two seconds, a 200 ms throttle updates the header about 10 times. Debounce gives you the final state after activity; throttle gives regular updates during activity.
Q2. Implement debounce.
Keep a timer in a closure; each call clears the previous timer and starts a new one that calls the original function with the latest arguments after the wait:
📄 snippet
function debounce(fn, wait) {
let timer;
return function (...args) {
clearTimeout(timer);
timer = setTimeout(() => fn.apply(this, args), wait);
};
}
Mention extensions: leading/trailing options, cancel and flush, maxWait, and preserving this with a regular function and apply.
Q3. What is memoization and when should you not use it?
Caching a function’s results keyed by its arguments, so repeated inputs skip the computation. Avoid it for impure functions (time, randomness, external state), when inputs rarely repeat (the cache only costs memory), when arguments are large objects that are expensive to turn into keys, and without a size limit or expiry in long-running processes.
Q4. How do debounce and throttle affect automated UI tests?
They delay or drop the app’s reaction to input, so checking state immediately after typing or scrolling gives false failures, and fixed sleeps give slow, still-flaky tests. Use retrying assertions, wait for the network request the debounced code triggers, or control time with fake clocks (Playwright page.clock, node:test mock.timers). Also test the behaviour itself: one request per pause, no double submit on a rapid double click.
❓ Frequently Asked Questions
🤔 Should I write my own debounce or use lodash?
For production code, a well-tested library function (lodash.debounce, lodash.throttle) handles edge cases such as maxWait and this-binding. Writing your own is a great exercise and a common interview task.
🤔 What is requestAnimationFrame throttling?
In the browser, scheduling work with requestAnimationFrame runs it at most once per frame (about 60 times a second), a natural throttle for visual updates during scroll or resize.
🤔 Is React useMemo the same as memoization?
Yes in spirit: it caches a computed value between renders until its dependencies change. React.memo and useCallback apply the same idea to components and functions.
🤔 Do fake timers work with async/await?
Yes, but promises still resolve on the microtask queue. After ticking, you may need to await a resolved promise so pending callbacks run; Playwright’s and Node’s clocks also offer async helpers for this.
🏁 Summary
- Debounce runs once after events stop; throttle runs at most once per interval while events continue.
- Leading-edge debounce blocks double submits; cancel and flush control pending calls.
- Memoization caches results of pure functions; cache promises to deduplicate async requests; bound the cache.
- Fake timers (node:test mock.timers, Playwright page.clock) make time-based code fast and deterministic to test.
- In UI tests, wait for outcomes with retrying assertions instead of fixed sleeps when debounce or throttle is involved.
Next, continue with Lesson 69: Node.js Test Runner. This completes Module 13. Module 14 is about testing JavaScript: the built-in Node.js test runner, Jest and Vitest, and the bridge to Playwright.
🎬 Watch JavaScript and automation tutorials on YouTube!
Subscribe to SqaToolsByDY • Practice on sqatools.in