Fix stale closure in delayed autosave callback
intermediate
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'Public interview reports
These public, self-reported interview accounts informed this practice version. The exercise is modelled on reported rounds, not copied from them, and the reports are not verified official questions or endorsements.
- Taro: Stripe frontend engineer interview, 2023
One Stripe front end engineer account lists a round on bug finding within an unknown project. This debug exercise practises that shape in a small codebase; it is not the reported bug.
Reported in a public Stripe interview account. Stripe frontend interview questions
Solution
1
The fixed code
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
Guides
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
Built in public
The code behind FrontendAtlas lives on GitHub. A star helps other frontend engineers find it.