A callback can call back into its owner before the outer operation finishes. This is reentrancy; it does not require threads. Listener dispatch is a useful small example: a listener can subscribe another listener or unsubscribe itself while emit is iterating.
Choose an iteration policy. Iterating a snapshot means newly added listeners wait until the next emission. With the simple snapshot policy below, a listener removed during an emission can still run if it was already in that snapshot. A stricter active-membership check is a different contract; neither should be accidental.
For this exercise subscriptions have token identity. Two subscriptions using the same callback are independent. Cleanup is idempotent: calling its returned function twice is harmless. Callback exceptions deliberately stop this synchronous dispatch; a real API should document whether it propagates, isolates or aggregates failures.
This standalone lab prepares you to inspect callback side effects in the pool. It is not an event-emitter feature secretly included in the capstone.
Predict, run, and explain
Write the output and trace the important state changes before checking it. Then run the program. Each editor is independent. Async examples end with main() so this editor waits for their work.
const listeners = new Set();
listeners.add(() => {
console.log("A");
listeners.add(() => console.log("late"));
});
listeners.add(() => console.log("B"));
for (const listener of [...listeners]) {
listener();
}
console.log(listeners.size);Check your prediction
A
B
3Define what happens during an ongoing dispatch
A callback can change the collection being dispatched or invoke the owner again before its current call returns. This is reentrancy, and it can happen without threads. A snapshot gives one dispatch a stable set of registrations, but does not prohibit nested dispatch.
Subscription identity must be chosen independently of callback identity. If registering the same function twice creates two subscriptions, each registration needs a separate token. Unsubscribing one must not remove the other accidentally.
const events = [];
const listeners = new Set();
let added = false;
listeners.add(() => {
events.push("first");
if (!added) {
added = true;
listeners.add(() => events.push("late"));
}
});
for (const listener of [...listeners]) {
listener();
}
console.log(events.join(","));
for (const listener of [...listeners]) {
listener();
}
console.log(events.join(","));Check your prediction
first
first,first,lateLate is absent from the first captured array and present in the second. Iterating the live Set would follow a different policy and can even keep growing during dispatch.
const callback = () => {};
const functions = new Set([callback, callback]);
const tokens = new Set([{ callback }, { callback }]);
console.log(functions.size);
console.log(tokens.size);Check your prediction
1
2The same function identity collapses in a Set; separate token objects do not. Neither collection is wrong in isolation, but only one fits independent duplicate subscriptions.
Try the rule on new inputs
Test addition, removal and a guarded nested emit from inside a callback. Write the expected call order before running. Never introduce unbounded recursive emission as a casual timing experiment.
When a listener calls the owner back
Changing the listener list is the mild case. The classic reentrancy bug is a listener that calls a method on the owner while the owner is half-way through an update. Below, a cart notifies listeners when an item is added; one listener adds a free gift when the cart reaches two items. The same code runs twice, once with the bug and once with the fix. Predict both lines.
function createCart(fixed) {
const items = [];
let total = 0;
const listeners = [];
let dispatching = false;
let again = false;
function notify() {
if (fixed && dispatching) {
again = true; // finish the current dispatch first
return;
}
dispatching = true;
do {
again = false;
for (const listener of listeners) listener(cart);
} while (again);
dispatching = false;
}
const cart = {
get count() {
return items.length;
},
get total() {
return total;
},
has: name => items.some(item => item.name === name),
subscribe: listener => listeners.push(listener),
add(item) {
items.push(item);
if (fixed) {
total += item.price;
notify();
} else {
notify();
total += item.price; // listeners ran before this line
}
}
};
return cart;
}
for (const fixed of [false, true]) {
const cart = createCart(fixed);
const seen = [];
cart.subscribe(c => seen.push(`${c.count}:${c.total}`));
cart.subscribe(c => {
if (c.count === 2 && !c.has("gift")) c.add({ name: "gift", price: 0 });
});
cart.add({ name: "apple", price: 3 });
cart.add({ name: "pear", price: 5 });
console.log(`${fixed ? "fixed" : "buggy"}: ${seen.join(" ")} | final ${cart.total}`);
}Check your prediction
buggy: 1:0 2:3 3:3 | final 8
fixed: 1:3 2:8 3:8 | final 8Each entry is count:total as the first listener saw it. In the buggy cart, add notifies between items.push and total += ..., so every listener runs while the cart is half-updated: 1:0 says one item costs nothing. When the pear arrives, the gift listener calls add again from inside the dispatch; that nested add notifies at once, so 3:3 is logged before the outer add has added the pear's 5. The final total is right, but nobody was told it. The fixed cart applies two rules. It finishes every state change before calling user code, and while a dispatch is running a nested notify only sets again, so the current round completes and one more round runs afterwards. Every listener now sees a consistent cart, and the nested change is reported after the one that caused it.
Trace the contract before building
A callback can change the owner's collections while the owner is still dispatching. That happens within one JavaScript stack and requires no threads. Decide whether new listeners join the current emission or wait for the next one.
For a snapshot policy, copy membership before invoking user code. Test a listener that adds another listener, removes itself and triggers another operation. State whether an already-snapshotted removed listener still runs. Different policies can be valid, but an implementation should not inherit accidental behavior from iterating a live mutable collection without a deliberate decision.
Your turn
Callbacks & Reentrancy: practice
Write subscribe and emit using a Set of subscription records, not a Set of functions. subscribe returns idempotent cleanup. Subscribe the same function twice, remove one subscription and emit: it should print tick once.
// Each subscribe call should allocate its own token record.Hint 1: the idea
Callback identity and subscription identity are different.
Hint 2: a first step
Store { callback } in the Set and close over that record in the cleanup function.
Show one solution
const subscriptions = new Set();
function subscribe(callback) {
const token = { callback };
subscriptions.add(token);
return () => {
subscriptions.delete(token);
};
}
function emit() {
for (const token of [...subscriptions]) {
token.callback();
}
}
const callback = () => console.log("tick");
const remove = subscribe(callback);
subscribe(callback);
remove();
remove();
emit();tickEach subscribe call creates its own token object, so subscribing the same function twice puts two different records in the Set. A Set of functions would have stored callback once, and remove() would then have removed the only subscription and printed nothing. The cleanup closes over its own token, so it can only ever delete that one registration, and Set.delete on a missing value does nothing, which makes the second remove() harmless. emit iterates a copy, so a callback that subscribes or unsubscribes during dispatch cannot change who is called in this round.
Change it and test it
Test a callback subscribing another callback during emit and explain why the new subscription waits. Then remove a later subscription during dispatch and verify the documented snapshot policy. Write a different contract only if you also update its tests.
Completion is saved in this browser only. It does not measure mastery.