Skip to content

Instantly share code, notes, and snippets.

@samuelcolvin
Created November 24, 2023 16:29
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save samuelcolvin/e795b3b5a78d1a47dce2c9740633b85c to your computer and use it in GitHub Desktop.
Save samuelcolvin/e795b3b5a78d1a47dce2c9740633b85c to your computer and use it in GitHub Desktop.
// this is lightly better than simple debounce as:
// 1. it kicks of a new search immediately
// 2. it waits for a server re
function debounceLoadOptions(searchUrl: string) {
let running = false
let runNext: [string, OptionsCallback] | null = null
const run = (inputValue: string, callback: OptionsCallback, force: boolean) => {
if (running && !force) {
runNext = [inputValue, callback]
} else {
running = true
request({
url: searchUrl,
query: {q: inputValue},
}).then(([, response]) => {
const {options} = response as { options: SearchOption[] }
callback(options)
if (runNext) {
const [nextInputValue, nextCallback] = runNext
runNext = null
run(nextInputValue, nextCallback, true)
} else {
running = false
}
})
}
}
return (inputValue: string, callback: OptionsCallback) => run(inputValue, callback, false)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment