js-common-code/src/classes/TimeWatch.js
2025-03-20 21:56:10 +09:00

70 lines
1.7 KiB
JavaScript

/**
* TimeWatch class
* @class
* @classdesc TimeWatch class to measure elapsed time
*/
class TimeWatch{
/**
* TimeWatch constructor
* @constructor
* @description TimeWatch constructor
* @param {number} startTime - start time
* @param {number} endTime - end time
*/
constructor(){
this.startTime = 0;
this.endTime = 0;
}
/**
* Start the timer
* @function
* @description Start the timer
*/
start(){
this.startTime = new Date().getTime();
}
/**
* Stop the timer
* @function
* @description Stop the timer
*/
stop(){
this.endTime = new Date().getTime();
}
/**
* Get the elapsed time
* @function
* @description Get the elapsed time
* @param {string} unit - unit of time (ms, s, min, h)
* @returns {number} - elapsed time
*/
getElapsedTime(unit = "ms") {
const elapsedTime = this.endTime - this.startTime;
switch (unit) {
case "s":
return elapsedTime / 1000;
case "min":
return elapsedTime / (1000 * 60);
case "h":
return elapsedTime / (1000 * 60 * 60);
case "ms":
default:
return elapsedTime;
}
}
/**
* Print the elapsed time
* @function
* @description Print the elapsed time
* @param {string} unit - unit of time (ms, s, min, h)
*/
printElapsedTime(unit = "ms") {
console.log(`Elapsed Time: ${this.getElapsedTime(unit)} ${unit}`);
}
}
// commonJS module
module.exports = TimeWatch;