1 | ;
|
2 |
|
3 | /**
|
4 | * A timer that calls callbacks while it is running, and when it expires.
|
5 | * @constructor
|
6 | * @alias Splat.Timer
|
7 | * @param {simulationCallback} onTick Called when the Timer is {@link Splat.Timer#tick tick()}ed
|
8 | * @param {number} expireMillis The number of milliseconds until the Timer expires
|
9 | * @param {emptyCallback} onExpire Called when the Timer expires
|
10 | */
|
11 | function Timer(onTick, expireMillis, onExpire) {
|
12 | /**
|
13 | * Called when the Timer is {@link Splat.Timer#tick tick()}ed
|
14 | * @member {tickCallback}
|
15 | * @private
|
16 | */
|
17 | this.onTick = onTick;
|
18 | /**
|
19 | * The number of milliseconds until the Timer expires.
|
20 | * When {@link Splat.Timer#time} reaches this number, the Timer will be expired, and {@link Splat.Timer#onExpire} will be called.
|
21 | * @member {number}
|
22 | * @private
|
23 | */
|
24 | this.expireMillis = expireMillis;
|
25 | /**
|
26 | * Called when the Timer expires.
|
27 | * @member {expireCallback}
|
28 | * @private
|
29 | */
|
30 | this.onExpire = onExpire;
|
31 | /**
|
32 | * Whether or not the Timer is currently running.
|
33 | * @member {boolean}
|
34 | * @private
|
35 | */
|
36 | this.running = false;
|
37 | /**
|
38 | * How long the Timer has run in milliseconds.
|
39 | * @member {number}
|
40 | * @private
|
41 | */
|
42 | this.time = 0;
|
43 | }
|
44 | /**
|
45 | * Start the Timer running.
|
46 | * This does not {@link Splat.Timer#reset reset} the Timer!
|
47 | */
|
48 | Timer.prototype.start = function() {
|
49 | this.running = true;
|
50 | };
|
51 | /**
|
52 | * Stop the Timer.
|
53 | * This does not {@link Splat.Timer#reset reset} the Timer!
|
54 | */
|
55 | Timer.prototype.stop = function() {
|
56 | this.running = false;
|
57 | };
|
58 | /**
|
59 | * Zeroes the timer.
|
60 | * This does not {@link Splat.Timer#stop stop} the Timer!
|
61 | */
|
62 | Timer.prototype.reset = function() {
|
63 | this.time = 0;
|
64 | };
|
65 | /**
|
66 | * Advance the Timer.
|
67 | * Normally {@link Splat.Scene} does this for you.
|
68 | * @param {number} elapsedMillis How many milliseconds to advance the timer.
|
69 | */
|
70 | Timer.prototype.tick = function(elapsedMillis) {
|
71 | if (!this.running) {
|
72 | return;
|
73 | }
|
74 | this.time += elapsedMillis;
|
75 | if (this.expired()) {
|
76 | this.stop();
|
77 | if (typeof this.onExpire === "function") {
|
78 | this.onExpire.call(this);
|
79 | }
|
80 | return;
|
81 | }
|
82 |
|
83 | if (typeof this.onTick === "function") {
|
84 | this.onTick.call(this, elapsedMillis);
|
85 | }
|
86 | };
|
87 | /**
|
88 | * Test if the Timer has expired.
|
89 | * @returns {boolean}
|
90 | */
|
91 | Timer.prototype.expired = function() {
|
92 | return typeof this.expireMillis !== "undefined" && this.time >= this.expireMillis;
|
93 | };
|
94 |
|
95 | module.exports = Timer;
|