Created
November 24, 2023 16:29
-
-
Save samuelcolvin/e795b3b5a78d1a47dce2c9740633b85c to your computer and use it in GitHub Desktop.
This file contains 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
// 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