File tree Expand file tree Collapse file tree
Expand file tree Collapse file tree Original file line number Diff line number Diff line change @@ -131,7 +131,7 @@ debouncedSave('data2'); // This will run after the first save completes
131131
132132### Autosave
133133
134- For autosave, use ** trailing** debounce (default) to save only after the user stops typing :
134+ For autosave, combine trailing debounce with serialization to prevent concurrent saves from racing :
135135
136136``` js
137137import pDebounce from ' p-debounce' ;
@@ -143,14 +143,17 @@ const saveDocument = async content => {
143143 });
144144};
145145
146- const autosave = pDebounce (saveDocument, 1000 );
146+ // Serialize saves, then debounce keystrokes
147+ const serializedSave = pDebounce .promise (saveDocument, {after: true });
148+ const autosave = pDebounce (serializedSave, 1000 );
147149
148150textArea .addEventListener (' input' , () => {
149151 autosave (textArea .value );
150152});
151153
152- // Saves 1 second after typing stops.
153- // If user types during save, starts new 1s timer after that keystroke.
154+ // 1. Waits 1s after typing stops
155+ // 2. If user types during save, queues next save with latest content
156+ // 3. Prevents race conditions where slow saves overwrite newer data
154157```
155158
156159## Related
You can’t perform that action at this time.
0 commit comments