Skip to content

Instantly share code, notes, and snippets.

@ccnokes
Created May 31, 2017 18:46
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 ccnokes/45b247781388fff7925592437b697248 to your computer and use it in GitHub Desktop.
Save ccnokes/45b247781388fff7925592437b697248 to your computer and use it in GitHub Desktop.
Make an async function take at least X amount of time
/**
* make an async function take at least X amount of time
* @param limit - in ms
* @param fn - returns promise
* @returns {Promise.<T>}
*/
function waitAtLeast(limit, fn) {
let start = Date.now();
let end = start + limit;
return fn().then(result => {
let now = Date.now();
if((now - start) > end) {
return result;
}
else {
return sleep(end - now).then(() => result);
}
});
}
// promisified setTimeout
function sleep(ms) {
return new Promise((res, rej) => {
setTimeout(res, ms);
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment