Forked from Nicknyr/Call function synchronously while iterating through array elements
Created
December 9, 2017 23:41
-
-
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
This file contains 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
/** | |
* 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