Created
May 31, 2017 18:46
-
-
Save ccnokes/45b247781388fff7925592437b697248 to your computer and use it in GitHub Desktop.
Make an async function take at least X amount of time
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
/** | |
* 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