Skip to content

Instantly share code, notes, and snippets.

@sbrl
Created Dec 22, 2019
Embed
What would you like to do?
[Stopwatch.mjs] C#'s System.Diagnostics.Stopwatch (roughly) implemented in C#.
"use strict";
/**
* Stopwatch class for timing things.
* Based on System.Diagnostics.Stopwatch from .NET: https://docs.microsoft.com/en-us/dotnet/api/system.diagnostics.stopwatch
*/
class Stopwatch {
/**
* Creates a new (stopped) stopwatch.
*/
constructor() {
this.start = null;
this.end = null;
this.is_high_resolution = false;
}
/**
* The number of seconds that have elapsed since the stopwatch was started.
* @return {number}
*/
get elapsed_seconds() {
return (this.end == null ? new Date() : this.end) - this.start;
}
/**
* The number of milliseconds that have elapsed since the stopwatch was started.
* @return {number}
*/
get elapsed_milliseconds() {
return this.elapsed_seconds / 1000;
}
/**
* Whether the stopwatch is currently running or not.
* @return {number}
*/
get is_running() {
return this.start !== null && this.end !== null;
}
/**
* Starts the stopwatch.
*/
start() {
this.start = new Date();
this.end = null;
}
/**
* Resets the stopwatch, stopping it and wiping the internal state in the
* process.
*/
reset() {
this.start = null;
this.end = null;
}
/**
* Restarts the stopwatch, keeping it running.
*/
restart() {
this.start();
}
/**
* Stops the stopwatch.
*/
stop() {
this.end = new Date();
}
/**
* Stops the stopwatch and returns the number of elapsed seconds.
* @return {number} The number of seconds elapsed since the stopwatch was started, as a float.
*/
end() {
this.stop();
return this.elapsed_seconds;
}
/**
* Returns a string that represents this stopwatch instance.
* @return {string}
*/
toString() {
return `[StopWatch, start=${start || "null"}, end=${end || "null"} | elapsed_seconds=${this.elapsed_seconds}]`;
}
}
/**
* Creates a new stopwatch, starts it, and returns the result.
* @return {Stopwatch} A new started stopwatch.
*/
function start_new() {
let result = new Stopwatch();
result.start();
return result;
}
Stopwatch.StartNew = start_new;
export { start_new };
export default Stopwatch;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment