FrontendAtlas
Interview Questions
Home>JavaScript interview questions> JavaScript coding challenges >Fix stale closure in delayed autosave callback

Fix stale closure in delayed autosave callback

intermediate
By FrontendAtlas Editorial · Updated Mar 31, 2026
A teammate tried to make autosave "predictable" by capturing the current draft when wiring a delayed callback. That feels reasonable until the user keeps typing: the callback keeps saving the old draft it closed over instead of the latest one. Fix the bug so delayed saves read fresh state at execution time.
Examples
const autosave = createDraftAutosave('hel');
let flush;
autosave.install(cb => { flush = cb; }, value => value);
autosave.setDraft('hello');
flush(); // 'hello'

const autosave = createDraftAutosave('a');
let flush;
autosave.install(cb => { flush = cb; }, value => value);
autosave.setDraft('ab');
flush(); // 'ab'
autosave.setDraft('abc');
flush(); // 'abc'

Solution

Overview

export default function createDraftAutosave(initialDraft = ''){

let draft = initialDraft;

return {

setDraft(nextDraft){

draft = nextDraft;

},

install(register, save){

// Read the current draft when the callback runs, not when it is registered.

return register(() => save(draft));

}

};

}

Similar questions

Fix lost `this` binding in callback registrationintermediateFix missing return in `map` / `filter`easyFix numeric sort in `sortScores`easy

Guides

Frontend interview preparation guideGuideFrontend coding interview questions and prep guideBlueprintJavaScript Problems That Actually Show UpBlueprintBuild Great UI in 60 MinutesBlueprint

Preparing for interviews? Use Frontend Coding Challenges first, then move into a concrete Study Plan before targeted Company Prep.

Open frontend interview questionsBrowse JavaScript interview questionsOpen Essential 60Open Machine Coding HubOpen Frontend Coding ChallengesOpen System DesignOpen Interview Prep GuideOpen System Design BlueprintOpen Framework Prep PathsOpen Study PlansOpen JavaScript mastery study planOpen Company PrepOpen JavaScript Framework Prep Guide
↗Incidents hub
← Prev←6 / 8Next →→