-
-
Notifications
You must be signed in to change notification settings - Fork 65
/
mutex.js
43 lines (41 loc) · 857 Bytes
/
mutex.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
/**
* Mutual exclude for JavaScript.
*
* @module mutex
*/
/**
* @callback mutex
* @param {function():void} cb Only executed when this mutex is not in the current stack
* @param {function():void} [elseCb] Executed when this mutex is in the current stack
*/
/**
* Creates a mutual exclude function with the following property:
*
* ```js
* const mutex = createMutex()
* mutex(() => {
* // This function is immediately executed
* mutex(() => {
* // This function is not executed, as the mutex is already active.
* })
* })
* ```
*
* @return {mutex} A mutual exclude function
* @public
*/
export const createMutex = () => {
let token = true
return (f, g) => {
if (token) {
token = false
try {
f()
} finally {
token = true
}
} else if (g !== undefined) {
g()
}
}
}