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
  | 
/**
 * @author ydq
 * @date 2019/05/28
 * @description 公共事件锁
 */
class _Locker {
    _locker: any = { key: false };
    _timeOut: any = { key: false };
    clear(): void {
        this._locker = { key: false };
    }
    // 获取锁状态
    get(key: string): boolean {
        return this._locker[key];
    }
    // 锁
    lock(key: string): boolean {
        this._locker[key] = true;
        return true;
    }
    // 解锁
    unlock(key: string): boolean {
        this._locker[key] = false;
        return false;
    }
    /**
     * 可以自动解锁的 锁
     * 获取 key锁 的状态
     * 如果 没有锁 则上锁,并在 500 毫秒后自动解锁
     * 如果 在锁 则返回上锁状态
     * @param {*} key
     * @param {*} time
     */
    autoLocker(key: string, time = 500): boolean {
        let _res = !!this._locker[key];
        if (_res === false) {
            this._locker[key] = true;
            clearTimeout(this._timeOut[key]);
            this._timeOut[key] = setTimeout(() => {
                this._locker[key] = false;
            }, time);
            return false;
        }
        return true;
    }
}
export default new _Locker();
  |