Debounce waits until calls stop for wait ms and then runs once with the last arguments: every call clears the timer and starts a new one. Throttle runs at most once per wait ms; the good version runs the first call at once and the last call when the window ends, so the final value isn't lost. groupBy walks the list once and pushes each item into the array for its key (today that's Object.groupBy). cloneDeep copies recursively, keeps a WeakMap of what it has copied so cycles and shared references survive, and copies Date, RegExp, Map and Set by type (today structuredClone covers most of this). Interviewers check this and arguments are kept, leading/trailing edges, cancel/flush, and cycles.
Implement Lodash functions: debounce(), throttle(), cloneDeep(), groupBy()
Answer it out loud, in your own words. Then compare.
Interviewers listen for how you get there, not only where you land. The answer opens once you have tried.
Debounce clears and restarts one timer on every call, so only a call followed by wait ms of quiet goes through. Throttle remembers when it last ran and drops calls inside the window. Both forward this and the arguments with fn.apply(this, args), which is why the returned function is a regular function, not an arrow. This basic throttle drops the last call of a burst, which the next stage fixes.
// Debounce: run once the calls have stopped for `wait` ms (the last call wins).function debounce(fn, wait) {let timer;return function (...args) {clearTimeout(timer); // every call restarts the countdowntimer = setTimeout(() => fn.apply(this, args), wait);};}// Throttle: run at most once per `wait` ms; calls in between are dropped.function throttle(fn, wait) {let last = -Infinity;return function (...args) {const now = Date.now();if (now - last >= wait) {last = now;fn.apply(this, args);}};}
passes 3 checks run on every build, against the native method where there is one
- debounce runs once, after the calls stop, with the last arguments
- debounce keeps this
- throttle runs at most once per window
Real debounce needs options. Leading runs the first call of a burst at once (a button that shouldn't double-submit); trailing runs the last one when it settles; with both, a single call runs once, not twice. cancel() drops a pending call (a component unmounting), and flush() runs it now (saving before navigation). Throttle with both edges runs the first call immediately and the latest call when the window closes, and that trailing call opens a new window, so calls are never closer than wait. groupBy returns a null-prototype object, as Object.groupBy does, so "constructor" and "__proto__" are ordinary keys.
function debounce(fn, wait, { leading = false, trailing = true } = {}) {let timer;let pendingArgs; // the latest call not yet deliveredlet pendingThis;let result;const run = () => {const args = pendingArgs;const ctx = pendingThis;pendingArgs = pendingThis = undefined;result = fn.apply(ctx, args);return result;};const expire = () => {timer = undefined;if (trailing && pendingArgs) run();pendingArgs = pendingThis = undefined;};function debounced(...args) {const startsBurst = timer === undefined;pendingArgs = args;pendingThis = this;clearTimeout(timer);timer = setTimeout(expire, wait);// Leading: call at the start of a burst. A single call is not repeated on the trailing edge,// because run() has already taken its arguments.if (startsBurst && leading) run();return result;}debounced.cancel = () => {clearTimeout(timer);timer = pendingArgs = pendingThis = undefined;};debounced.flush = () => {if (timer !== undefined) {clearTimeout(timer);expire();}return result;};return debounced;}// Throttle with both edges (lodash's default): the first call runs at once, the last call in a// window runs when the window ends, so the final value is never lost.function throttle(fn, wait, { leading = true, trailing = true } = {}) {let timer;let pendingArgs;let pendingThis;const run = () => {const args = pendingArgs;const ctx = pendingThis;pendingArgs = pendingThis = undefined;fn.apply(ctx, args);};const expire = () => {timer = undefined;if (trailing && pendingArgs) {run();timer = setTimeout(expire, wait); // a trailing call opens a new window}};return function throttled(...args) {pendingArgs = args;pendingThis = this;if (timer === undefined) {if (leading) run();timer = setTimeout(expire, wait);}};}// Group by a key name or a function. A null-prototype object, like Object.groupBy, so a key such// as "constructor" or "__proto__" is just a key.function groupBy(items, key) {const keyOf = typeof key === 'function' ? key : (item) => item[key];const groups = Object.create(null);let index = 0;for (const item of items) {const k = keyOf(item, index++);(groups[k] ??= []).push(item);}return groups;}
passes 9 checks run on every build, against the native method where there is one
- debounce: one burst gives one trailing call with the last arguments
- debounce leading: the first call runs at once, the last at the end
- debounce leading: a single call runs once, not twice
- debounce cancel drops the pending call; flush runs it now
- throttle: leading and trailing, never closer than the wait
- throttle: the last value is not lost
- throttle trailing: false drops calls inside the window
- groupBy matches Object.groupBy
- groupBy: keys like __proto__ and constructor are ordinary keys
Recursing into own keys is the easy part. A WeakMap from original to copy, filled before recursing, makes cycles terminate and keeps two references to one object pointing at one copy. Date, RegExp, Map, Set and typed arrays have their state outside own properties, so each is copied by type. Object.create(Object.getPrototypeOf(value)) keeps class instances working; Reflect.ownKeys includes symbol keys; arrays keep their holes. Functions are shared, not cloned (lodash returns {} for a function at the top level). Very deep data can still overflow the stack; structuredClone is the built-in for data that has no functions or class instances.
function cloneDeep(value, seen = new WeakMap()) {// Primitives are copies already; functions are shared, not cloned.if (value === null || typeof value !== 'object') return value;// Seen before: a cycle or a shared reference. Return the same copy, so the shape is kept.if (seen.has(value)) return seen.get(value);if (value instanceof Date) return new Date(value.getTime());if (value instanceof RegExp) {const copy = new RegExp(value.source, value.flags);copy.lastIndex = value.lastIndex;return copy;}if (value instanceof Map) {const copy = new Map();seen.set(value, copy);value.forEach((v, k) => copy.set(cloneDeep(k, seen), cloneDeep(v, seen)));return copy;}if (value instanceof Set) {const copy = new Set();seen.set(value, copy);value.forEach((v) => copy.add(cloneDeep(v, seen)));return copy;}if (ArrayBuffer.isView(value) && !(value instanceof DataView)) return new value.constructor(value);// Arrays keep their length and holes; objects keep their prototype (class instances stay instances).const copy = Array.isArray(value) ? new Array(value.length) : Object.create(Object.getPrototypeOf(value));seen.set(value, copy); // before recursing, or a cycle recurses foreverfor (const key of Reflect.ownKeys(value)) {if (!Object.prototype.propertyIsEnumerable.call(value, key)) continue; // own enumerable keys, symbols toocopy[key] = cloneDeep(value[key], seen);}return copy;}
passes 7 checks run on every build, against the native method where there is one
- nested objects and arrays are independent copies
- agrees with a JSON round trip on JSON data
- cycles: the copy points at itself, not at the original
- a shared reference stays shared in the copy
- Date, RegExp, Map, Set and typed arrays are copied, not shared
- class instances stay instances
- holes, symbol keys, and functions shared
Search as you type
A search box should ask the server once the user pauses, not on every keystroke: debounce the request by about 300 ms. In React, create the debounced function once (useMemo or useRef) and cancel() it on unmount; recreating it on every render is a common agent bug that makes the debounce do nothing.
Scroll and resize handlers
Scroll and resize fire many times a frame. Throttle the work (or schedule it with requestAnimationFrame) so position checks run at a steady rate, and keep the trailing call so the final position is handled.
The built-ins that replaced two of them
Object.groupBy (ES2024) groups into a null-prototype object, and Map.groupBy groups by any value. structuredClone deep-copies plain data, including cycles, Date, Map and Set, but throws on functions and drops class prototypes.
Creating the debounced function inside a React render: each render gets a new timer, so nothing is ever debounced.
Writing the wrapper as an arrow function:
thisis lost, so methods break.A throttle without a trailing call: the last scroll position or the final keystroke is silently dropped.
No
cancel()on unmount: a debounced call fires after the component is gone and sets state on it.groupByinto{}: a key of"constructor"findsObject.prototype.constructorinstead of an empty slot.JSON.parse(JSON.stringify(x))as a deep clone: it turnsDateinto strings, dropsundefined,MapandSet, and throws on cycles.Recording the copy in the
WeakMapafter recursing: a cycle then recurses forever.
When would you choose debounce over throttle?
Debounce when only the final state matters (search query, auto-save after typing, window resize relayout). Throttle when you need steady updates during the activity (scroll position, drag, progress reporting).
How does lodash implement throttle?
As a debounce with maxWait equal to wait: the function must run at least once every wait ms even while calls keep coming, which gives leading and trailing calls at a steady rate.
How do you test timing code like this?
With a fake clock: replace setTimeout and Date.now, then advance time by hand (vi.useFakeTimers() and vi.advanceTimersByTime() in Vitest). The checks on this page run that way.
What can structuredClone not copy?
Functions and DOM nodes throw a DataCloneError. Class instances come back as plain objects (their prototype is dropped), and property descriptors, getters and symbol keys are not kept.
- lodash.com/docs/4.17.15#debounce
- lodash.com/docs/4.17.15#throttle
- lodash.com/docs/4.17.15#cloneDeep
- developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/groupBy
- developer.mozilla.org/en-US/docs/Web/API/Window/structuredClone
- developer.mozilla.org/en-US/docs/Web/API/Web_Workers_API/Structured_clone_algorithm
- developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/WeakMap
- developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/apply