Skip to content

Virtual whiteboard for sketching hand-drawn like diagrams

Debounce localstorage save (#328)

Christopher Chedeau3db7d69849ac
diff --git a/src/index.tsx b/src/index.tsx
index b2e3169048..5f9a82f034 100644
--- a/src/index.tsx
+++ b/src/index.tsx
@@ -28,7 +28,7 @@ import { renderScene } from "./renderer";
import { AppState } from "./types";
import { ExcalidrawElement, ExcalidrawTextElement } from "./element/types";
-import { getDateTime, isInputLike, measureText } from "./utils";
+import { getDateTime, isInputLike, measureText, debounce } from "./utils";
import { KEYS, META_KEY, isArrowKey } from "./keys";
import { findShapeByKey, shapesShortcutKeys } from "./shapes";
@@ -1016,13 +1016,17 @@ export class App extends React.Component<{}, AppState> {
}
}
+ private saveDebounced = debounce(() => {
+ saveToLocalStorage(elements, this.state);
+ }, 300);
+
componentDidUpdate() {
renderScene(elements, this.rc!, this.canvas!, {
scrollX: this.state.scrollX,
scrollY: this.state.scrollY,
viewBackgroundColor: this.state.viewBackgroundColor
});
- saveToLocalStorage(elements, this.state);
+ this.saveDebounced();
if (history.isRecording()) {
history.pushEntry(history.generateCurrentEntry(elements));
history.clearRedoStack();
diff --git a/src/utils.ts b/src/utils.ts
index 4043c5a4cc..32147dc45d 100644
--- a/src/utils.ts
+++ b/src/utils.ts
@@ -51,3 +51,14 @@ export function measureText(text: string, font: string) {
return { width, height, baseline };
}
+
+export function debounce<T extends any[]>(
+ fn: (...args: T) => void,
+ timeout: number
+) {
+ let handle = 0;
+ return (...args: T) => {
+ clearTimeout(handle);
+ handle = window.setTimeout(() => fn(...args), timeout);
+ };
+}