Skip to content

Instantly share code, notes, and snippets.

@tecfu
Created February 3, 2022 03:59
Show Gist options
  • Save tecfu/833624fefbf5256c137d5a923a0df06c to your computer and use it in GitHub Desktop.
Save tecfu/833624fefbf5256c137d5a923a0df06c to your computer and use it in GitHub Desktop.
Javscript execute promises sequentially, subject to delay
/**
* How to execute a list of functions subject to a delay
*/
const interval = 3000
const delay = time => new Promise(resolve => setTimeout(resolve, time))
// in practice, this would be an array of functions with nested callbacks
const fns = Array(3).fill((() => console.log(Date.now())))
// wait for each delay before executing the next function
async function delayJobs () {
var response = []
// works
for(var i = 0; i < fns.length; i++) {
if(i !== 0) await delay(interval)
response.push(fns[i]())
}
// works
//for(fn of fns) {
// await delay(interval)
// response.push(fn())
//}
// doesn't work, executes in parallel
//fns.map( async (fn, i) => {
// if(i !== 0) await delay(interval)
// response.push(fns[i]())
//})
return response
}
delayJobs()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment