/
Iteration.js
85 lines (71 loc) · 2.01 KB
/
Iteration.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
const Debounce = require('./Debounce')
/**
* Restrain execution of given function to every set iteration
* @function Iteration
* @method process - Main process or logic
*/
function Iteration() {
/**
* Tracks iterations
* @property {number} iteration
*/
let iteration
/**
* Has iteration been idle?
* @property {boolean} idle = true
*/
let isIdle = true
/** Holds debounce instance - Used for reseting of **isIdle** */
let debounce
/**
* Main process or logic
* @function process
* @param {function} func - callback function
* @param {number} delay - execute every **delay**:nth iteration
* @param {Object} [options] - optional params for additional configuration
* @param {boolean} [options.cancel = false] - cancels and resets iteration
* @param {boolean} [options.init = true] - toggles initial execute
* @param {number} [options.startFrom = 0] - configuring of initial starting iteration
* @param {number} [options.idleResetDelay = delay*1.5] - delay between last execution and being considerd _idle_
*/
this.process = (func, delay, options = {}) => {
const {
cancel = false,
init = true,
startFrom = 0,
idleResetDelay = 500,
} = options
// allows configuring of initial starting iteration (default 0)
if(iteration === undefined) iteration = startFrom
return new Promise(resolve => {
iteration++
// cancels and resets iteration
if(cancel) {
cancelIteration()
return
}
// initial execution
if(init) {
if(isIdle) executeFunc()
// cancels iteration opon being idle
if(debounce === undefined) debounce = (new Debounce()).process
debounce(() => cancelIteration(), idleResetDelay)
}
// resets counter **iteration** opon execution
if(iteration === delay) {
iteration = 0
executeFunc()
}
function executeFunc() {
func()
isIdle = false
resolve('function executed')
}
function cancelIteration() {
isIdle = true
debounce = iteration = undefined
}
})
}
}
module.exports = Iteration