Files
yjs/lib/mutex.js

32 lines
591 B
JavaScript
Raw Normal View History

2018-03-23 04:35:52 +01:00
/**
* Creates a mutual exclude function with the following property:
*
* @example
* const mutex = createMutex()
2018-11-25 03:17:00 +01:00
* mutex(() => {
2018-03-23 04:35:52 +01:00
* // This function is immediately executed
2018-11-25 03:17:00 +01:00
* mutex(() => {
* // This function is not executed, as the mutex is already active.
2018-03-23 04:35:52 +01:00
* })
* })
*
* @return {Function} A mutual exclude function
* @public
*/
export const createMutex = () => {
let token = true
return (f, g) => {
2018-01-10 00:17:26 +01:00
if (token) {
token = false
try {
f()
} finally {
token = true
2018-01-10 00:17:26 +01:00
}
2018-06-02 13:33:04 +02:00
} else if (g !== undefined) {
g()
2018-01-10 00:17:26 +01:00
}
}
}