Skip to content

Commit

Permalink
Simplifying arguments passed
Browse files Browse the repository at this point in the history
  • Loading branch information
andyfleming committed Nov 25, 2017
1 parent 442ff25 commit d74678b
Showing 1 changed file with 33 additions and 32 deletions.
65 changes: 33 additions & 32 deletions src/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -11,41 +11,42 @@ function interval(func, intervalLength, options = {}) {
const settings = Object.assign(defaults, options)

return new Promise((rootPromiseResolve, rootPromiseReject) => {
callFunction(func, intervalLength, settings, 1, rootPromiseResolve, rootPromiseReject)
})
}

function callFunction(func, intervalLength, settings, currentIteration, rootPromiseResolve, rootPromiseReject) {

let stopRequested = false
const stop = () => {
stopRequested = true
}

const callNext = () => {
// If we've hit the desired number of iterations, or stop was called, resolve the root promise and return
if (currentIteration === settings.iterations || stopRequested) {
rootPromiseResolve()
return
}

// Otherwise, call the next iteration
callFunction(func, intervalLength, settings, currentIteration + 1, rootPromiseResolve, rootPromiseReject)
}

const calculatedIntervalLength = (typeof intervalLength === 'function') ? intervalLength(currentIteration + 1) : intervalLength

// Call the user function after the desired interval length. After, call the next iteration (and/or handle error)
setTimeout(() => {
func(currentIteration, stop).then(callNext).catch(err => {
if (!settings.stopOnError) {
callNext()
return
const callFunction = currentIteration => {

let stopRequested = false
const stop = () => {
stopRequested = true
}

const callNext = () => {
// If we've hit the desired number of iterations, or stop was called, resolve the root promise and return
if (currentIteration === settings.iterations || stopRequested) {
rootPromiseResolve()
return
}

// Otherwise, call the next iteration
callFunction(currentIteration + 1)
}

const calculatedIntervalLength = (typeof intervalLength === 'function') ? intervalLength(currentIteration + 1) : intervalLength

// Call the user function after the desired interval length. After, call the next iteration (and/or handle error)
setTimeout(() => {
func(currentIteration, stop).then(callNext).catch(err => {
if (!settings.stopOnError) {
callNext()
return
}

rootPromiseReject(err)
})
}, calculatedIntervalLength)
}

rootPromiseReject(err)
})
}, calculatedIntervalLength)
callFunction(1)
})
}

module.exports = interval

0 comments on commit d74678b

Please sign in to comment.