-
Notifications
You must be signed in to change notification settings - Fork 0
/
Timeout.js
53 lines (41 loc) · 1.01 KB
/
Timeout.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
const Timeout = (() => {
const keyId = {}
const complete = {}
// set(key, func, ms) -- user-defined key
// set(func, ms) -- func used as key
//
// returns a function allowing you to test if it has executed
const set = (...args) => {
let key, func, ms
if (args.length == 3)
[key, func, ms] = args
else {
[func, ms] = args
key = func
}
clear(key)
const invoke = () => (complete[key] = true, func())
keyId[key] = setTimeout(invoke, ms)
complete[key] = false
return () => executed(key)
}
const clear = key => {
clearTimeout(keyId[key])
delete keyId[key]
delete complete[key]
}
// timeout has been created
const exists = key => key in keyId
// timeout does exist, but has not yet run
const pending = key => exists(key) && !executed(key)
// test if a timeout has run
const executed = key => key in complete && complete[key]
return {
set,
clear,
exists,
pending,
executed
}
})()
module.exports = Timeout;