Created
July 12, 2024 08:00
-
-
Save BrianHung/5171f9ba587c80c4cdfcff27b780ee5f to your computer and use it in GitHub Desktop.
debounced codemirror autocomplete
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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