Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@bjoerge
Created March 16, 2016 16:20
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bjoerge/8351ea730cc85d441431 to your computer and use it in GitHub Desktop.
Save bjoerge/8351ea730cc85d441431 to your computer and use it in GitHub Desktop.
Emit values of an array over time
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