|
| 1 | +/** |
| 2 | + *@author Nandan V |
| 3 | + * Sunday, 26 July 2020 8:33 AM |
| 4 | + *@description Singleton class that handles the <b>timing of tests</b> and |
| 5 | + * specs. <br/> The class is singleton as <u>javascript does not support |
| 6 | + * multiple timer instances<u/>. |
| 7 | + */ |
| 8 | +classIntervalTimer{ |
| 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, |
| 16 | +callBack=()=>{}){ |
| 17 | +this.prevInterval=0 |
| 18 | +if(this.instance==null){ |
| 19 | +this.interval=interval |
| 20 | +this.callBack=callBack |
| 21 | +this.instance=this |
| 22 | +}else{ |
| 23 | +returnthis.instance |
| 24 | +} |
| 25 | +} |
| 26 | + |
| 27 | +/** |
| 28 | + *@description Starts the timer. |
| 29 | + */ |
| 30 | +startTimer(){ |
| 31 | +this.timer=setInterval(this.callBack,this.interval) |
| 32 | +} |
| 33 | + |
| 34 | +/** |
| 35 | + *@description Resets the timer. |
| 36 | + *@return {number} Elapsed time in milliseconds. |
| 37 | + */ |
| 38 | +resetTimer(){ |
| 39 | +clearInterval(this.timer) |
| 40 | +this.callBack=()=>{} |
| 41 | +returnthis.getElapsedTime() |
| 42 | +} |
| 43 | + |
| 44 | +/** |
| 45 | + *@return {number} Elapsed time in milliseconds since reset. |
| 46 | + */ |
| 47 | +getElapsedTime(offset=0){ |
| 48 | +this.timeElapsed=this.timer-this.prevInterval |
| 49 | +this.prevInterval=this.timer |
| 50 | +returnthis.timeElapsed-offset |
| 51 | +} |
| 52 | + |
| 53 | +/** |
| 54 | + *@return {number} Elapsed time since start. |
| 55 | + */ |
| 56 | +getRunTime(){ |
| 57 | +returnthis.timer |
| 58 | +} |
| 59 | +} |
| 60 | + |
| 61 | +/** |
| 62 | + *@author Nandan V |
| 63 | + * Saturday, 01 August 2020 8:33 AM |
| 64 | + *@description Example usage |
| 65 | + */ |
| 66 | +constExampleIntervalTimer=function(){ |
| 67 | +/** |
| 68 | + * Create am object with default settings. |
| 69 | + *@type {IntervalTimer} Used to get timing information. |
| 70 | + */ |
| 71 | +consttimer=newIntervalTimer() |
| 72 | +timer.startTimer() |
| 73 | + |
| 74 | +// ... Initialization code ... |
| 75 | +// I generally use it for timing tests in Jasmine JS. |
| 76 | + |
| 77 | +/** |
| 78 | + * Gets the runtime till this point. |
| 79 | + * Can be subtracted from ElapsedTime to offset timing of initialization code. |
| 80 | + */ |
| 81 | +constinitOffset=timer.getRunTime() |
| 82 | + |
| 83 | +// ... A test ... |
| 84 | +// The time taken to run the test. |
| 85 | +console.log(timer.getElapsedTime(initOffset)) |
| 86 | + |
| 87 | +/** |
| 88 | + * Returns the elapsed time and resets the timer to 0. |
| 89 | + */ |
| 90 | +console.log(timer.resetTimer()) |
| 91 | +} |
| 92 | + |
| 93 | +ExampleIntervalTimer() |