diff --git a/src/extension.ts b/src/extension.ts index ec44f75..e7a4058 100644 --- a/src/extension.ts +++ b/src/extension.ts @@ -1,14 +1,14 @@ import * as vscode from 'vscode' import { getDecorations } from './decoration' +import { debounce } from './utils' export function activate(context: vscode.ExtensionContext) { let tokenSource: vscode.CancellationTokenSource let currentDecorations: Awaited> = [] - context.subscriptions.push( - vscode.window.onDidChangeTextEditorSelection(async (event) => { - tokenSource?.cancel() + const updateDecorations = debounce( + async (event: vscode.TextEditorSelectionChangeEvent) => { tokenSource = new vscode.CancellationTokenSource() const token = tokenSource.token @@ -28,6 +28,14 @@ export function activate(context: vscode.ExtensionContext) { new vscode.Selection(line, 0, line, 0), ]) ) + }, + () => 50 + ) + + context.subscriptions.push( + vscode.window.onDidChangeTextEditorSelection((event) => { + tokenSource?.cancel() + updateDecorations(event) }) ) } diff --git a/src/utils.ts b/src/utils.ts new file mode 100644 index 0000000..3fe82f6 --- /dev/null +++ b/src/utils.ts @@ -0,0 +1,16 @@ +export function debounce unknown>( + fn: T, + getMs: () => number +) { + let timer: NodeJS.Timeout + return (...args: Parameters) => { + clearTimeout(timer) + + const ms = getMs() + if (ms > 0) { + timer = setTimeout(() => fn(...args), getMs()) + } else { + fn(...args) + } + } +}