Debouncing & Throttling
Published by Brayan K
Modern JavaScript applications rely heavily on real-time interactions—scrolling, resizing, typing, mouse movement, search bars, touch gestures, infinite feeds, and dynamic UI. These events can fire dozens to hundreds of times per second, and without control, they can destroy performance, cause UI lag, freeze the browser, and produce unnecessary network calls.
Part of the free JavaScript course at LearnCodingFast — hands-on lessons with examples you run in your browser, plus practice exercises and a quick quiz.
Specify which calls survive
Debouncing and throttling change when a function is allowed to run; they do not make the function’s own work cheaper. Here, trailing debounce keeps the latest call after a quiet interval. Leading-only throttle invokes the first eligible call and drops calls inside its interval. Those are explicit policies, not the only possible implementations.
function createClock() {
let current = 0, nextId = 0;
const jobs = new Map();
return {
now: () => current,
set(callback, delay) { const id = nextId++; jobs.set(id, { at: current + delay, callback }); return id; },
clear(id) { jobs.delete(id); },
advance(amount) {
const target = current + amount;
for (;;) {
const next = [...jobs].filter(([, job]) => job.at <= target)
.sort((a, b) => a[1].at - b[1].at || a[0] - b[0])[0];
if (!next) break;
jobs.delete(next[0]); current = next[1].at; next[1].callback();
}
current = target;
},
pending: () => jobs.size
};
}
function debounceTrailing(fn, wait, clock) {
"use strict";
if (typeof fn !== "function") throw new TypeError("fn must be a function");
if (!Number.isInteger(wait) || wait < 1 || wait > 60000) throw new RangeError("wait must be an integer from 1 to 60000");
let timer = null, latestArgs = null, latestThis = null;
function invoke() {
if (timer === null) return undefined;
const args = latestArgs, receiver = latestThis;
timer = null; latestArgs = null; latestThis = null;
return fn.apply(receiver, args);
}
function wrapped(...args) {
if (timer !== null) clock.clear(timer);
latestArgs = args; latestThis = this;
timer = clock.set(invoke, wait);
}
wrapped.cancel = () => {
if (timer !== null) clock.clear(timer);
timer = null; latestArgs = null; latestThis = null;
};
wrapped.flush = () => {
if (timer === null) return undefined;
clock.clear(timer);
return invoke();
};
wrapped.pending = () => timer !== null;
return wrapped;
}
const clock = createClock(); // This is a controlled test scheduler, not a wall clock.
const calls = [];
const search = debounceTrailing(value => calls.push(value), 10, clock);
search("c");
clock.advance(6);
search("ca"); // Reset the quiet interval and keep this latest argument.
clock.advance(9);
console.log(calls.length, search.pending());
clock.advance(1); // Reach the latest request's deadline in this controlled model.
console.log(calls.join(","), search.pending(), clock.pending());
// ✅ Expected output:
// 0 true
// ca false 0No browser timing or elapsed-time result is claimed. The tiny scheduler stores jobs and lets the test advance them in deadline/insertion order; it does not simulate microtasks, rendering or background-tab throttling. The 1–60000 wait range is this exercise’s validation contract. Event Loop, Microtasks & Async Internals owns real timer scheduling and Performance Optimization owns measuring the work that matters.
Creating a new wrapper for every event defeats shared state
function createClock() {
let current = 0, nextId = 0;
const jobs = new Map();
return {
now: () => current,
set(callback, delay) { const id = nextId++; jobs.set(id, { at: current + delay, callback }); return id; },
clear(id) { jobs.delete(id); },
advance(amount) {
const target = current + amount;
for (;;) {
const next = [...jobs].filter(([, job]) => job.at <= target)
.sort((a, b) => a[1].at - b[1].at || a[0] - b[0])[0];
if (!next) break;
jobs.delete(next[0]); current = next[1].at; next[1].callback();
}
current = target;
},
pending: () => jobs.size
};
}
function debounceTrailing(fn, wait, clock) {
"use strict";
if (typeof fn !== "function") throw new TypeError("fn must be a function");
if (!Number.isInteger(wait) || wait < 1 || wait > 60000) throw new RangeError("wait must be an integer from 1 to 60000");
let timer = null, latestArgs = null, latestThis = null;
function invoke() {
if (timer === null) return undefined;
const args = latestArgs, receiver = latestThis;
timer = null; latestArgs = null; latestThis = null;
return fn.apply(receiver, args);
}
function wrapped(...args) {
if (timer !== null) clock.clear(timer);
latestArgs = args; latestThis = this;
timer = clock.set(invoke, wait);
}
wrapped.cancel = () => {
if (timer !== null) clock.clear(timer);
timer = null; latestArgs = null; latestThis = null;
};
wrapped.flush = () => {
if (timer === null) return undefined;
clock.clear(timer);
return invoke();
};
wrapped.pending = () => timer !== null;
return wrapped;
}
const clock = createClock();
const calls = [];
const save = value => calls.push(value);
debounceTrailing(save, 10, clock)("A");
debounceTrailing(save, 10, clock)("B");
clock.advance(10);
console.log(calls.join(","));
// ✅ Expected output:
// A,BCreate one wrapper for the subscription lifetime, keep its reference for removal, and cancel it during cleanup. Recreating wrappers inside an input handler creates unrelated timer state. Framework renders can create the same problem if a wrapper’s lifetime is not managed. Closures and Scope owns per-factory state; Events owns exact listener identity for removal.
function createClock() {
let current = 0, nextId = 0;
const jobs = new Map();
return {
now: () => current,
set(callback, delay) { const id = nextId++; jobs.set(id, { at: current + delay, callback }); return id; },
clear(id) { jobs.delete(id); },
advance(amount) {
const target = current + amount;
for (;;) {
const next = [...jobs].filter(([, job]) => job.at <= target)
.sort((a, b) => a[1].at - b[1].at || a[0] - b[0])[0];
if (!next) break;
jobs.delete(next[0]); current = next[1].at; next[1].callback();
}
current = target;
},
pending: () => jobs.size
};
}
const clock = createClock();
let calls = 0;
const handle = clock.set(() => calls++, 5);
console.log(handle === 0);
if (handle !== null) clock.clear(handle);
clock.advance(5);
console.log(calls);
// ✅ Expected output:
// true
// 0The fake scheduler deliberately starts handles at zero. A truthiness check would fail to cancel that job. Real timer handle representations differ between hosts; the implementation treats them as opaque and reserves null for “no pending job.”
Retain the latest receiver and arguments, not merely the callback
function createClock() {
let current = 0, nextId = 0;
const jobs = new Map();
return {
now: () => current,
set(callback, delay) { const id = nextId++; jobs.set(id, { at: current + delay, callback }); return id; },
clear(id) { jobs.delete(id); },
advance(amount) {
const target = current + amount;
for (;;) {
const next = [...jobs].filter(([, job]) => job.at <= target)
.sort((a, b) => a[1].at - b[1].at || a[0] - b[0])[0];
if (!next) break;
jobs.delete(next[0]); current = next[1].at; next[1].callback();
}
current = target;
},
pending: () => jobs.size
};
}
function debounceTrailing(fn, wait, clock) {
"use strict";
if (typeof fn !== "function") throw new TypeError("fn must be a function");
if (!Number.isInteger(wait) || wait < 1 || wait > 60000) throw new RangeError("wait must be an integer from 1 to 60000");
let timer = null, latestArgs = null, latestThis = null;
function invoke() {
if (timer === null) return undefined;
const args = latestArgs, receiver = latestThis;
timer = null; latestArgs = null; latestThis = null;
return fn.apply(receiver, args);
}
function wrapped(...args) {
if (timer !== null) clock.clear(timer);
latestArgs = args; latestThis = this;
timer = clock.set(invoke, wait);
}
wrapped.cancel = () => {
if (timer !== null) clock.clear(timer);
timer = null; latestArgs = null; latestThis = null;
};
wrapped.flush = () => {
if (timer === null) return undefined;
clock.clear(timer);
return invoke();
};
wrapped.pending = () => timer !== null;
return wrapped;
}
const clock = createClock();
const calls = [];
const save = debounceTrailing(function (value) { calls.push(this.name + ":" + value); }, 10, clock);
save.call({ name: "first" }, "A");
save.call({ name: "second" }, "B");
clock.advance(10);
console.log(calls.join(","));
function strictReceiver() { "use strict"; return this; }
const receiverCheck = debounceTrailing(strictReceiver, 10, clock);
receiverCheck();
console.log("plain receiver", receiverCheck.flush() === strictReceiver());
receiverCheck.call(7);
console.log("primitive receiver", receiverCheck.flush() === strictReceiver.call(7));
receiverCheck.call(null);
console.log("null receiver", receiverCheck.flush() === strictReceiver.call(null));
// ✅ Expected output:
// second:B
// plain receiver true
// primitive receiver true
// null receiver truefunction createClock() {
let current = 0, nextId = 0;
const jobs = new Map();
return {
now: () => current,
set(callback, delay) { const id = nextId++; jobs.set(id, { at: current + delay, callback }); return id; },
clear(id) { jobs.delete(id); },
advance(amount) {
const target = current + amount;
for (;;) {
const next = [...jobs].filter(([, job]) => job.at <= target)
.sort((a, b) => a[1].at - b[1].at || a[0] - b[0])[0];
if (!next) break;
jobs.delete(next[0]); current = next[1].at; next[1].callback();
}
current = target;
},
pending: () => jobs.size
};
}
function debounceTrailing(fn, wait, clock) {
"use strict";
if (typeof fn !== "function") throw new TypeError("fn must be a function");
if (!Number.isInteger(wait) || wait < 1 || wait > 60000) throw new RangeError("wait must be an integer from 1 to 60000");
let timer = null, latestArgs = null, latestThis = null;
function invoke() {
if (timer === null) return undefined;
const args = latestArgs, receiver = latestThis;
timer = null; latestArgs = null; latestThis = null;
return fn.apply(receiver, args);
}
function wrapped(...args) {
if (timer !== null) clock.clear(timer);
latestArgs = args; latestThis = this;
timer = clock.set(invoke, wait);
}
wrapped.cancel = () => {
if (timer !== null) clock.clear(timer);
timer = null; latestArgs = null; latestThis = null;
};
wrapped.flush = () => {
if (timer === null) return undefined;
clock.clear(timer);
return invoke();
};
wrapped.pending = () => timer !== null;
return wrapped;
}
const clock = createClock();
const calls = [];
const save = debounceTrailing(value => calls.push(value.text), 10, clock);
const payload = { text: "before" };
save(payload);
payload.text = "after";
clock.advance(10);
console.log(calls.join(","));
// ✅ Expected output:
// afterBoth wrapper factories use strict mode so plain calls retain undefined and primitive receivers are not boxed before forwarding. The debounce wrapper stores references. Read a primitive input value at the event boundary when you need that value rather than a later read from an event or mutable object. An arrow wrapper would capture its surrounding this instead of receiving the caller’s this. The this Keyword owns receiver semantics; Deep Copy vs Shallow Copy & Data Structures owns stronger copy boundaries.
Cancel, flush and return values are different operations
function createClock() {
let current = 0, nextId = 0;
const jobs = new Map();
return {
now: () => current,
set(callback, delay) { const id = nextId++; jobs.set(id, { at: current + delay, callback }); return id; },
clear(id) { jobs.delete(id); },
advance(amount) {
const target = current + amount;
for (;;) {
const next = [...jobs].filter(([, job]) => job.at <= target)
.sort((a, b) => a[1].at - b[1].at || a[0] - b[0])[0];
if (!next) break;
jobs.delete(next[0]); current = next[1].at; next[1].callback();
}
current = target;
},
pending: () => jobs.size
};
}
function debounceTrailing(fn, wait, clock) {
"use strict";
if (typeof fn !== "function") throw new TypeError("fn must be a function");
if (!Number.isInteger(wait) || wait < 1 || wait > 60000) throw new RangeError("wait must be an integer from 1 to 60000");
let timer = null, latestArgs = null, latestThis = null;
function invoke() {
if (timer === null) return undefined;
const args = latestArgs, receiver = latestThis;
timer = null; latestArgs = null; latestThis = null;
return fn.apply(receiver, args);
}
function wrapped(...args) {
if (timer !== null) clock.clear(timer);
latestArgs = args; latestThis = this;
timer = clock.set(invoke, wait);
}
wrapped.cancel = () => {
if (timer !== null) clock.clear(timer);
timer = null; latestArgs = null; latestThis = null;
};
wrapped.flush = () => {
if (timer === null) return undefined;
clock.clear(timer);
return invoke();
};
wrapped.pending = () => timer !== null;
return wrapped;
}
const clock = createClock();
const calls = [];
const save = debounceTrailing(value => { calls.push(value); return value.toUpperCase(); }, 10, clock);
console.log(save("discard"), save.pending());
save.cancel(); save.cancel();
clock.advance(10);
console.log(calls.length, save.pending());
save("keep");
console.log(save.flush(), save.pending(), clock.pending());
console.log(save.flush());
clock.advance(10);
console.log(calls.join(","));
// ✅ Expected output:
// undefined true
// 0 false
// KEEP false 0
// undefined
// keepCalling save schedules work and returns undefined; it is not a promise for the eventual result. Flush synchronously returns the pending invocation’s result, while a second flush has nothing to invoke. Cancel discards pending work but cannot undo work that has already started. A promise-returning debounce needs an additional policy for replaced callers, failures and cancellation.
function createClock() {
let current = 0, nextId = 0;
const jobs = new Map();
return {
now: () => current,
set(callback, delay) { const id = nextId++; jobs.set(id, { at: current + delay, callback }); return id; },
clear(id) { jobs.delete(id); },
advance(amount) {
const target = current + amount;
for (;;) {
const next = [...jobs].filter(([, job]) => job.at <= target)
.sort((a, b) => a[1].at - b[1].at || a[0] - b[0])[0];
if (!next) break;
jobs.delete(next[0]); current = next[1].at; next[1].callback();
}
current = target;
},
pending: () => jobs.size
};
}
function debounceTrailing(fn, wait, clock) {
"use strict";
if (typeof fn !== "function") throw new TypeError("fn must be a function");
if (!Number.isInteger(wait) || wait < 1 || wait > 60000) throw new RangeError("wait must be an integer from 1 to 60000");
let timer = null, latestArgs = null, latestThis = null;
function invoke() {
if (timer === null) return undefined;
const args = latestArgs, receiver = latestThis;
timer = null; latestArgs = null; latestThis = null;
return fn.apply(receiver, args);
}
function wrapped(...args) {
if (timer !== null) clock.clear(timer);
latestArgs = args; latestThis = this;
timer = clock.set(invoke, wait);
}
wrapped.cancel = () => {
if (timer !== null) clock.clear(timer);
timer = null; latestArgs = null; latestThis = null;
};
wrapped.flush = () => {
if (timer === null) return undefined;
clock.clear(timer);
return invoke();
};
wrapped.pending = () => timer !== null;
return wrapped;
}
const clock = createClock();
const calls = [];
let save;
save = debounceTrailing(value => {
calls.push(value);
if (value === "A") save("B");
}, 10, clock);
save("A");
save.flush();
console.log(calls.join(","), save.pending());
clock.advance(10);
console.log(calls.join(","), save.pending());
// ✅ Expected output:
// A true
// A,B falseThe callback schedules B during A’s invocation. Clearing the fields after the callback would erase that new request. Detaching before invoking user code gives the new request its own lifecycle.
function createClock() {
let current = 0, nextId = 0;
const jobs = new Map();
return {
now: () => current,
set(callback, delay) { const id = nextId++; jobs.set(id, { at: current + delay, callback }); return id; },
clear(id) { jobs.delete(id); },
advance(amount) {
const target = current + amount;
for (;;) {
const next = [...jobs].filter(([, job]) => job.at <= target)
.sort((a, b) => a[1].at - b[1].at || a[0] - b[0])[0];
if (!next) break;
jobs.delete(next[0]); current = next[1].at; next[1].callback();
}
current = target;
},
pending: () => jobs.size
};
}
function debounceTrailing(fn, wait, clock) {
"use strict";
if (typeof fn !== "function") throw new TypeError("fn must be a function");
if (!Number.isInteger(wait) || wait < 1 || wait > 60000) throw new RangeError("wait must be an integer from 1 to 60000");
let timer = null, latestArgs = null, latestThis = null;
function invoke() {
if (timer === null) return undefined;
const args = latestArgs, receiver = latestThis;
timer = null; latestArgs = null; latestThis = null;
return fn.apply(receiver, args);
}
function wrapped(...args) {
if (timer !== null) clock.clear(timer);
latestArgs = args; latestThis = this;
timer = clock.set(invoke, wait);
}
wrapped.cancel = () => {
if (timer !== null) clock.clear(timer);
timer = null; latestArgs = null; latestThis = null;
};
wrapped.flush = () => {
if (timer === null) return undefined;
clock.clear(timer);
return invoke();
};
wrapped.pending = () => timer !== null;
return wrapped;
}
const clock = createClock();
const failure = new Error("save failed");
const save = debounceTrailing(() => { throw failure; }, 10, clock);
save();
try { save.flush(); } catch (error) { console.log(error === failure); }
console.log(save.pending(), clock.pending());
// ✅ Expected output:
// true
// false 0A synchronous flush failure reaches the flush caller. A real timer callback runs later, outside the original scheduling call’s try/catch. The wrapper does not swallow errors, and it does not observe a returned rejected promise. Error Handling owns those exception boundaries.
Leading throttle and trailing debounce make different promises
function createClock() {
let current = 0, nextId = 0;
const jobs = new Map();
return {
now: () => current,
set(callback, delay) { const id = nextId++; jobs.set(id, { at: current + delay, callback }); return id; },
clear(id) { jobs.delete(id); },
advance(amount) {
const target = current + amount;
for (;;) {
const next = [...jobs].filter(([, job]) => job.at <= target)
.sort((a, b) => a[1].at - b[1].at || a[0] - b[0])[0];
if (!next) break;
jobs.delete(next[0]); current = next[1].at; next[1].callback();
}
current = target;
},
pending: () => jobs.size
};
}
function throttleLeading(fn, wait, clock) {
"use strict";
let previous = -Infinity;
return function (...args) {
const current = clock.now();
if (current - previous < wait) return undefined;
previous = current;
return fn.apply(this, args);
};
}
const clock = createClock();
const calls = [];
const update = throttleLeading(value => calls.push(value), 10, clock);
update("A");
clock.advance(4); update("B");
clock.advance(5); update("C");
clock.advance(1); update("D");
clock.advance(20);
console.log(calls.join(","), clock.pending());
function strictReceiver() { "use strict"; return this; }
console.log("plain receiver", throttleLeading(strictReceiver, 10, clock)() === strictReceiver());
console.log("primitive receiver", throttleLeading(strictReceiver, 10, clock).call(7) === strictReceiver.call(7));
console.log("null receiver", throttleLeading(strictReceiver, 10, clock).call(null) === strictReceiver.call(null));
// ✅ Expected output:
// A,D 0
// plain receiver true
// primitive receiver true
// null receiver trueA is eligible immediately because previous starts at negative infinity. B and C are dropped; they are not remembered for later. D is eligible at the exact interval boundary in this model. A timestamp is one implementation technique, not a requirement for all throttles. A trailing throttle would need a timer and explicit latest-value and cleanup rules.
function createClock() {
let current = 0, nextId = 0;
const jobs = new Map();
return {
now: () => current,
set(callback, delay) { const id = nextId++; jobs.set(id, { at: current + delay, callback }); return id; },
clear(id) { jobs.delete(id); },
advance(amount) {
const target = current + amount;
for (;;) {
const next = [...jobs].filter(([, job]) => job.at <= target)
.sort((a, b) => a[1].at - b[1].at || a[0] - b[0])[0];
if (!next) break;
jobs.delete(next[0]); current = next[1].at; next[1].callback();
}
current = target;
},
pending: () => jobs.size
};
}
function debounceTrailing(fn, wait, clock) {
"use strict";
if (typeof fn !== "function") throw new TypeError("fn must be a function");
if (!Number.isInteger(wait) || wait < 1 || wait > 60000) throw new RangeError("wait must be an integer from 1 to 60000");
let timer = null, latestArgs = null, latestThis = null;
function invoke() {
if (timer === null) return undefined;
const args = latestArgs, receiver = latestThis;
timer = null; latestArgs = null; latestThis = null;
return fn.apply(receiver, args);
}
function wrapped(...args) {
if (timer !== null) clock.clear(timer);
latestArgs = args; latestThis = this;
timer = clock.set(invoke, wait);
}
wrapped.cancel = () => {
if (timer !== null) clock.clear(timer);
timer = null; latestArgs = null; latestThis = null;
};
wrapped.flush = () => {
if (timer === null) return undefined;
clock.clear(timer);
return invoke();
};
wrapped.pending = () => timer !== null;
return wrapped;
}
const clock = createClock();
const calls = [];
const update = debounceTrailing(value => calls.push(value), 10, clock);
for (const value of ["A", "B", "C", "D"]) {
update(value); clock.advance(9);
}
console.log(calls.length, update.pending());
clock.advance(1);
console.log(calls.join(","));
// ✅ Expected output:
// 0 true
// DWith continued calls before the quiet interval expires, this policy can keep waiting. A maximum-wait feature is a different contract; it is not secretly supplied here. Choose based on interaction needs: a final resize calculation and a continuing drag preview may need different policies. Avoid debouncing feedback that users need immediately.
Real timers and asynchronous requests need separate safeguards
The adapter calls both host timer functions through wrappers rather than rebinding them as methods of clock. This adapter check flushes and cancels, so its answer does not depend on elapsed time. A real timeout delay is an eligibility delay, not a precise appointment; busy work and browser policies can postpone it. requestAnimationFrame coordinates work with rendering opportunities rather than imposing a general millisecond throttle.
Debouncing when a request starts does not decide which response may update the UI. An older request can finish after a newer one. Advanced Scope, Closures & Lexical Environments owns invocation ownership, and AbortController & Cancelling Async Work owns cooperative cancellation. Canceling the pending debounce timer does not abort an in-flight request.
Guided exercise: retain only the latest pending callback
Fill each literal hint. This small manual queue isolates cancellation and the null sentinel; flushing it runs surviving jobs, not a real clock.
const jobs = new Map();
let next = 0, handle = null;
function schedule(value) {
if (handle !== ___) jobs.delete(handle); // 👉 replace ___ with null
handle = next++;
jobs.set(handle, () => console.log(value));
}
schedule("A"); schedule("B");
for (const callback of jobs.___()) callback(); // 👉 replace ___ with values
jobs.clear();
handle = ___; // 👉 replace ___ with null
console.log(jobs.size, handle === null);
// ✅ Expected output:
// B
// 0 trueIndependent brief: a reusable trailing debounce lifecycle
Implement debounceTrailing(fn, wait, clock) with a stable ordinary-function wrapper. The trusted injected clock provides set(callback, delay) and clear(handle), returning opaque handles that may be zero. Validate fn and the integer wait range 1–60000. Keep only the latest call’s receiver and arguments; the wrapper itself returns undefined. Provide pending(), cancel() and flush().
Cancel must clear pending work and references and be harmless when repeated. Flush must clear the scheduled job, invoke once and return its result or propagate its exact synchronous error. Detach state before calling fn so a reentrant request survives. Check latest arguments/receiver, zero handles, quiet-period reset, cancellation, repeated flush, return/error identity and reentrancy. The contract has no leading call, maximum wait, promise fan-out or in-flight cancellation.
Reference notes
MDN’s debounce and throttle entries distinguish the policies. The timer reference explains why delays can exceed the requested value. Controlled scheduling proves the wrapper’s stated state transitions, not frame rates or network freshness.
Practice quiz
What does this complete program print? const jobs=new Map([[0,()=>console.log("old")]]);const handle=0;if(handle!==null)jobs.delete(handle);console.log(jobs.size);
- 0
- 1
- undefined
- TypeError
Answer: 0. An explicit sentinel comparison handles zero correctly.
What does this complete program print? const calls=[];const wrap=()=>{let latest;return value=>{latest=value;return ()=>calls.push(latest)}};const a=wrap(),b=wrap();const runA=a("A"),runB=b("B");runA();runB();console.log(calls.join(","));
- B
- A,B
- A
- B,A
Answer: A,B. Separate wrapper instances retain separate state.
What does this complete program print? let latest;const item={value:"old"};latest=item;item.value="new";console.log(latest.value);
- old
- undefined
- new
- TypeError
Answer: new. Retaining a reference does not snapshot its fields.
What does this complete program print? const calls=[];function wrap(fn){return function(...args){return fn.apply(this,args)}}const run=wrap(function(value){calls.push(this.name+value)});run.call({name:"A"},"B");console.log(calls.join(","));
- undefinedB
- BA
- TypeError
- AB
Answer: AB. An ordinary wrapper can forward its call receiver.
What does this complete program print? let pending=true;let calls=0;function flush(){if(!pending)return;pending=false;calls++;return "done"}console.log(flush(),flush(),calls);
- done undefined 1
- done done 2
- undefined undefined 0
- done done 1
Answer: done undefined 1. Only the first flush has pending work to invoke.
What does this complete program print? let pending=true;function invoke(){pending=false;callback()}function callback(){pending=true}invoke();console.log(pending);
- false
- true
- undefined
- TypeError
Answer: true. Clearing before the callback preserves a reentrant request.
What does this complete program print? let previous=-Infinity;const calls=[];for(const point of [0,4,9,10]){if(point-previous>=10){previous=point;calls.push(point===0?"first":"boundary")}}console.log(calls.join(","));
- first
- boundary
- first,boundary
- first,first,boundary
Answer: first,boundary. Leading eligibility includes the first call and the exact interval boundary.
What does this complete program print? let pending=true;const reason={code:"failed"};try{pending=false;throw reason}catch(error){console.log(error===reason)}console.log(pending);
- true true
- false false
- false true
- true false
Answer: true false. Lifecycle cleanup can precede propagation of the original failure.
Continue this course
- Previous: Custom Event Emitters & Observer Pattern
- Next: DOM Reflow, Repaint & Browser Rendering Pipeline — How the browser converts HTML to pixels and how JS triggers reflows
- Quick reference: JavaScript cheat sheet