From ee7faef92bd7543876a57be06b39ba7e49562033 Mon Sep 17 00:00:00 2001 From: Alexander Kucera Date: Fri, 24 Oct 2025 13:13:49 +0200 Subject: [PATCH] Adds debounce mechanism for API key refresh Implements debounce timer to prevent excessive API calls when updating API key Prevents rapid repeated model refreshes by: - Adding a 500ms delay timer - Clearing previous timers to avoid multiple concurrent requests - Cleaning up timers when settings tab is hidden Improves performance and reduces unnecessary API load during key entry --- settings.ts | 28 ++++++++++++++++++++++++++-- 1 file changed, 26 insertions(+), 2 deletions(-) diff --git a/settings.ts b/settings.ts index 6bdf3b6..b7db14e 100644 --- a/settings.ts +++ b/settings.ts @@ -56,6 +56,10 @@ export class FreewritingPromptsSettingTab extends PluginSettingTab { private modelDropdown: DropdownComponent | null = null; /** Cached list of available models for the dropdown */ private availableModels: ModelOption[] = []; + /** Debounce timer for API key changes to avoid excessive API calls */ + private apiKeyDebounceTimer: number | null = null; + /** Debounce delay in milliseconds */ + private readonly API_KEY_DEBOUNCE_MS = 500; /** * Creates a new settings tab instance. @@ -68,6 +72,17 @@ export class FreewritingPromptsSettingTab extends PluginSettingTab { this.plugin = plugin; } + /** + * Cleanup method to clear any pending timers. + * Called when settings tab is closed or destroyed. + */ + hide(): void { + if (this.apiKeyDebounceTimer !== null) { + window.clearTimeout(this.apiKeyDebounceTimer); + this.apiKeyDebounceTimer = null; + } + } + /** * Renders the settings UI. * @@ -96,9 +111,18 @@ export class FreewritingPromptsSettingTab extends PluginSettingTab { await this.plugin.saveSettings(); this.plugin.promptGenerator.updateApiKey(value); - // Trigger model refresh when API key is entered + // Clear any existing debounce timer + if (this.apiKeyDebounceTimer !== null) { + window.clearTimeout(this.apiKeyDebounceTimer); + this.apiKeyDebounceTimer = null; + } + + // Debounce model refresh to avoid excessive API calls on every keystroke if (value.trim().length > 0) { - await this.refreshModels(); + this.apiKeyDebounceTimer = window.setTimeout(async () => { + await this.refreshModels(); + this.apiKeyDebounceTimer = null; + }, this.API_KEY_DEBOUNCE_MS); } })) .then(setting => {