Skip to content

Instantly share code, notes, and snippets.

@danieljsj
Forked from thommyhh/delay-promise.js
Last active October 26, 2018 23:34
Show Gist options
  • Save danieljsj/b8f66ca76bcd21cd2274c61ddab82f0a to your computer and use it in GitHub Desktop.
Save danieljsj/b8f66ca76bcd21cd2274c61ddab82f0a to your computer and use it in GitHub Desktop.
JavaScript delayed promise
// Sometimes it is helpful/necessary to create a promise, that delays the execution.
// This very general/generic 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)
})
}
// The next 3 lines of code are an example of how to use `delay()` in general:
delay(200, 1000).then(() => {
// your delayed code here
})
// We combine `fetch-mock` with `delay()` as follows:
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