A closure can retain far more than its callback appears to use. In a request handler, a delayed callback that needs only parsed.userId may nevertheless keep rawBody reachable because both variables belong to the enclosing function scope. The multi-megabyte body can therefore survive until the timer runs. section 9.1.1
Scope is also a garbage-collection concern: it supplies reachability paths. Assigning rawBody = null removes one path, but restructuring the code so the closure receives only userId prevents the unwanted path from existing. section 9.1.1
Use these rules when delayed work captures data:
- Inspect every variable in the enclosing function scope, not only the values referenced visibly inside the callback. section 9.1.1
- Prefer passing a small derived value into a separate scheduling function over exposing a large object to the closure. section 9.1.1
function processRequest(rawBody) {
const parsed = JSON.parse(rawBody);
setTimeout(() => {
sendNotification(parsed.userId);
}, 5000);
}
Shows the retention-prone request handler, where the callback's enclosing scope can keep rawBody reachable. section 9.1.1
function scheduleSendNotification(userId) {
setTimeout(() => {
sendNotification(userId)
}, 5000);
}
function processRequest(rawBody) {
const userId = JSON.parse(rawBody).userId;
scheduleSendNotification(userId);
}
Shows the safer restructuring: extract userId and give the timer closure access only to that small value. section 9.1.1























