Last active
July 21, 2023 21:43
-
-
Save thommyhh/71fa3bc49d9b38f84162bccea20e3522 to your computer and use it in GitHub Desktop.
JavaScript delayed promise
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
// Sometimes it is helpful/necessary to create a promise, that delays the execution. | |
// This snippet returns a promise, that is resolved after a given timeout. | |
// The `min` and `max` arguments are used to calcuate a random delay in the range between `min` and `max` | |
let delay = (min, max) => { | |
return new Promise(resolve => { | |
setTimeout(resolve, Math.random() * (max - min) + min) | |
}) | |
} | |
// In your actual code you use it as follows: | |
delay(200, 1000).then(() => { | |
// your delayed code here | |
}) | |
// I use the above for delaying mocked requests with the `fetch-mock` library. | |
fetchMock.mock('begin:/my/dummy/url', (url, options) => { | |
return delay(200, 1000).then(() => { | |
// my code creating the response object where I look at the options for post parameters | |
return responseObject | |
}) | |
}) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment