Skip to content

Instantly share code, notes, and snippets.

@BrianHung
Created July 12, 2024 08:00
Show Gist options
  • Save BrianHung/5171f9ba587c80c4cdfcff27b780ee5f to your computer and use it in GitHub Desktop.
Save BrianHung/5171f9ba587c80c4cdfcff27b780ee5f to your computer and use it in GitHub Desktop.
debounced codemirror autocomplete
export function debounceAutocompletion(
language: Language,
source: CompletionSource,
wait: number = 500,
) {
let currContext: CompletionContext;
let cancel = () => {}; // no-op
return [
language.data.of({
autocomplete: (context: CompletionContext) => {
currContext = context; // Use latest context.
cancel();
return null;
}
}),
language.data.of({
autocomplete: (context: CompletionContext) => {
currContext = context; // Use latest context.
cancel();
return new Promise(resolve => {
const timeoutId = window.setTimeout(async () => {
try {
const result = await source(currContext);
resolve(result);
} catch (error) {
resolve(null);
}
}, wait);
cancel = () => {
clearTimeout(timeoutId);
resolve(null);
}
context.addEventListener("abort", cancel);
});
}
}),
]
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment