-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathindex.js
36 lines (36 loc) · 1002 Bytes
/
index.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
module.exports = function (fn, relay, options = {}) {
const {modifier = 1.20, timeout = 1000, min = 1, max = 0} = options
let stress = 1
let cycle
function increase () {
const nextStress = stress * modifier
return (nextStress < max || !max) ? nextStress : max
}
function decrease () {
const nextStress = stress / modifier
return nextStress > min ? nextStress : min
}
function balance () {
const prevStress = stress
stress = relay() ? increase() : decrease()
return prevStress !== stress
}
function start (nextTimeout) {
cycle = setInterval(run, nextTimeout)
}
function run () {
const nextTimeout = timeout * stress
fn({stress, timeout: nextTimeout, cycle})
if (balance()) {
clear()
start(nextTimeout)
}
}
function clear () {
if (cycle) {
clearInterval(cycle)
}
}
start()
return clear
}