MCPcopy Create free account
hub / github.com/TheAlgorithms/JavaScript / IntervalTimer

Class IntervalTimer

Timing-Functions/IntervalTimer.js:8–58  ·  view source on GitHub ↗

* @author Nandan V * Sunday, 26 July 2020 8:33 AM * @description Singleton class that handles the timing of tests and * specs. The class is singleton as javascript does not support * multiple timer instances .

Source from the content-addressed store, hash-verified

6 * multiple timer instances<u/>.
7 */
8class IntervalTimer {
9 /**
10 * @description Constructor for Timer.
11 * @param interval Sets the interval for running the timer.
12 * @param callBack The callback function to be executed.
13 * @return {IntervalTimer} If exists, the existing object.
14 */
15 constructor(interval = 10, callBack = () => {}) {
16 this.prevInterval = 0
17 if (this.instance == null) {
18 this.interval = interval
19 this.callBack = callBack
20 this.instance = this
21 } else {
22 return this.instance
23 }
24 }
25
26 /**
27 * @description Starts the timer.
28 */
29 startTimer() {
30 this.timer = setInterval(this.callBack, this.interval)
31 }
32
33 /**
34 * @description Resets the timer.
35 * @return {number} Elapsed time in milliseconds.
36 */
37 resetTimer() {
38 clearInterval(this.timer)
39 this.callBack = () => {}
40 return this.getElapsedTime()
41 }
42
43 /**
44 * @return {number} Elapsed time in milliseconds since reset.
45 */
46 getElapsedTime(offset = 0) {
47 this.timeElapsed = this.timer - this.prevInterval
48 this.prevInterval = this.timer
49 return this.timeElapsed - offset
50 }
51
52 /**
53 * @return {number} Elapsed time since start.
54 */
55 getRunTime() {
56 return this.timer
57 }
58}
59
60/**
61 * @author Nandan V

Callers

nothing calls this directly

Calls

no outgoing calls

Tested by

no test coverage detected