Skip to content

Instantly share code, notes, and snippets.

@graup
Last active November 26, 2018 04:58
Show Gist options
  • Save graup/ba12ab52268d8e4193ea61935a76b0aa to your computer and use it in GitHub Desktop.
Save graup/ba12ab52268d8e4193ea61935a76b0aa to your computer and use it in GitHub Desktop.
const FAST_LOAD_TIME = 500;
const clamp = (num, min, max) => Math.min(Math.max(num, min), max);
function loadAndWait(minimumLoadTime = FAST_LOAD_TIME) {
const startedLoading = + new Date();
return function waitMinimum() {
return new Promise(resolve => {
const loadDuration = new Date() - startedLoading;
const waitTime = clamp(minimumLoadTime-loadDuration, 0, minimumLoadTime);
setTimeout(resolve, waitTime);
});
}
}
async function doSomething() {
const waitMinimum = loadAndWait();
// Do something that the user expects to take some time, e.g. loading data ...
await waitMinimum();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment