All files / src/Ice Timer.js

87.67% Statements 64/73
66.66% Branches 10/15
100% Functions 5/5
87.67% Lines 64/73

Press n or j to go to the next uncovered block, b, p or k for the previous block.

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 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 7441x 41x 41x 41x 41x 41x 41x 69x 69x 69x 69x 69x 41x 41x 67x 67x 67x 67x 41x 41x 13179x     13179x 13179x 13179x 13179x 13179x 13179x 13179x 13179x 13179x 41x 41x 12137x     12137x 12137x 12137x 32x 32x 12105x 12105x 12137x   12137x 12105x 12105x 12105x 12105x 12137x 41x 41x 1074x     1074x 1074x 1074x 1074x 1074x 1074x 1074x     1074x 1074x 41x 41x 41x 41x 41x  
// Copyright (c) ZeroC, Inc.
 
import { TimerUtil } from "./TimerUtil.js";
import { CommunicatorDestroyedException } from "./LocalExceptions.js";
 
export class Timer {
    constructor(logger) {
        this._logger = logger;
        this._destroyed = false;
        this._tokenId = 0;
        this._tokens = new Map();
    }
 
    destroy() {
        this._tokens.forEach((_, key) => this.cancel(key));
        this._destroyed = true;
        this._tokens.clear();
    }
 
    schedule(callback, delay) {
        if (this._destroyed) {
            throw new CommunicatorDestroyedException();
        }
        const token = this._tokenId++;
        const id = Timer.setTimeout(() => this.handleTimeout(token), delay);
        this._tokens.set(token, {
            callback: callback,
            id: id,
            isInterval: false,
        });
        return token;
    }
 
    cancel(id) {
        if (this._destroyed) {
            return false;
        }
 
        const token = this._tokens.get(id);
        if (token === undefined) {
            return false;
        }
 
        this._tokens.delete(id);
        if (token.isInterval) {
            Timer.clearInterval(token.id);
        } else {
            Timer.clearTimeout(token.id);
        }
 
        return true;
    }
 
    handleTimeout(id) {
        if (this._destroyed) {
            return;
        }
 
        const token = this._tokens.get(id);
        if (token !== undefined) {
            this._tokens.delete(id);
            try {
                token.callback();
            } catch (ex) {
                this._logger.warning("uncaught exception while executing timer:\n" + ex);
            }
        }
    }
}
 
Timer.setTimeout = TimerUtil.setTimeout;
Timer.clearTimeout = TimerUtil.clearTimeout;
Timer.setImmediate = TimerUtil.setImmediate;