Created
March 16, 2016 16:20
-
-
Save bjoerge/8351ea730cc85d441431 to your computer and use it in GitHub Desktop.
Emit values of an array over time
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
export default function replayer(array, opts = {}, emit) { | |
let idx = 0 | |
let timer | |
return { | |
start: next, | |
stop: stop, | |
reset: reset | |
} | |
function reset() { | |
idx = 0 | |
} | |
function stop() { | |
clearTimeout(timer) | |
} | |
function next() { | |
const last = idx === array.length - 1 | |
emit({ | |
type: 'item', | |
index: idx, | |
item: array[idx] | |
}) | |
if (last && opts.infinite !== false) { | |
return | |
} | |
idx = last ? 0 : idx + 1 | |
const wait = (typeof opts.wait === 'function') ? opts.wait(idx) : (opts.wait || 1000) | |
timer = setTimeout(next, wait) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment