Skip to content

Commit a1836fe

Browse files
committed
Improve
1 parent 01f66dc commit a1836fe

1 file changed

Lines changed: 7 additions & 4 deletions

File tree

readme.md

Lines changed: 7 additions & 4 deletions
Original file line numberDiff line numberDiff 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
137137
import 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

148150
textArea.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

0 commit comments

Comments
 (0)