Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save 0Prime/cfcdef0e136e78059132bfb290dd18f3 to your computer and use it in GitHub Desktop.
Save 0Prime/cfcdef0e136e78059132bfb290dd18f3 to your computer and use it in GitHub Desktop.
Javascript: Looping over an array and calling a function in a sychronous manner using setInterval
/**
* At specified interval takes next x of xs and calls f(x)
* Returns abort function, which stops iteration
* @param xs - arguments array for f
* @param f - a function
* @param delay - delay between calls, ms
*/
const intervalForEach = (xs, f, delay) => {
const gen = xs.entries()
const id = setInterval(() => {
const { done, value } = gen.next()
done ? clearInterval(id) : f(value[1])
}, delay)
return () => clearInterval(id)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment