From 68de05b5d28f55789dfc85e76cd78182e09f7884 Mon Sep 17 00:00:00 2001 From: Erin Schnabel Date: Fri, 21 Nov 2025 20:59:31 -0500 Subject: [PATCH] =?UTF-8?q?=F0=9F=90=9B=20debounce=20over=20Timer?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- README.md | 2 +- src/dn-Plugin.ts | 48 ++++++++++++++++++++++++++---------------------- 2 files changed, 27 insertions(+), 23 deletions(-) diff --git a/README.md b/README.md index 9291359..7e32340 100644 --- a/README.md +++ b/README.md @@ -220,7 +220,7 @@ npm run format # Format code ```txt src/ ├── @types/ - │ └── settings.d.ts # TypeScript interfaces + │ └── settings.d.ts # TypeScript interfaces ├── dn-Plugin.ts # Main plugin class ├── dn-CardParser.ts # Parse files into cards ├── dn-Modal.ts # Card display modal diff --git a/src/dn-Plugin.ts b/src/dn-Plugin.ts index 908a368..5229db6 100644 --- a/src/dn-Plugin.ts +++ b/src/dn-Plugin.ts @@ -1,4 +1,11 @@ -import { type Editor, Notice, Plugin, TFile, TFolder } from "obsidian"; +import { + debounce, + type Editor, + Notice, + Plugin, + TFile, + TFolder, +} from "obsidian"; import type { Card, DeckNotesData, DeckNotesSettings } from "./@types/settings"; import { DeckNotesApi } from "./dn-Api"; import { CardParser } from "./dn-CardParser"; @@ -12,7 +19,6 @@ export default class DeckNotesPlugin extends Plugin { cachedCards: Card[] = []; cardParser!: CardParser; api!: DeckNotesApi; - saveViewsTimer: NodeJS.Timeout | null = null; async onload() { console.debug("Loading Deck Notes plugin", `v${this.manifest.version}`); @@ -68,10 +74,8 @@ export default class DeckNotesPlugin extends Plugin { console.debug("Unloading Deck Notes plugin"); // Flush any pending view saves - if (this.saveViewsTimer) { - clearTimeout(this.saveViewsTimer); - void this.saveViews(); - } + this.debouncedSaveViews.cancel(); + void this.saveViews(); // Clear API reference if (window.deckNotes) { @@ -93,6 +97,21 @@ export default class DeckNotesPlugin extends Plugin { await this.scanCards(); } + debouncedSaveViews = debounce( + async () => { + await this.saveViews(); + }, + 2000, + true, // resetTimer: save only after 2s of no new views + ); + + async saveViews() { + await this.saveData({ + ...this.settings, + cardViews: this.data.cardViews, + }); + } + async scanCards() { this.cachedCards = []; @@ -159,22 +178,7 @@ export default class DeckNotesPlugin extends Plugin { recordView(cardKey: string) { this.data.cardViews[cardKey] = Date.now(); - - // Debounce saves: only write to disk after 2s of no card views - if (this.saveViewsTimer) { - clearTimeout(this.saveViewsTimer); - } - this.saveViewsTimer = setTimeout(() => { - void this.saveViews(); - }, 2000); - } - - async saveViews() { - this.saveViewsTimer = null; - await this.saveData({ - ...this.settings, - cardViews: this.data.cardViews, - }); + this.debouncedSaveViews(); } showCard() {