Utility class for measuring and tracking elapsed time.

The Timer class provides functionality to measure elapsed time with millisecond precision. It can be started, stopped, and reset, and supports different formatting options when converting to a string representation.

Example

// Create and start a new timer
const timer = new Timer();

// Do some work...

// Get the elapsed time
console.log(`Operation took ${timer.elapsed}ms`);

// Stop the timer
timer.stop();

// Convert to formatted string
console.log(timer.toString('seconds')); // e.g., "2.5s"

// Reset and reuse
timer.reset();

The Timer instance can be used directly in string contexts or arithmetic operations through its implementation of Symbol.toPrimitive.

Hierarchy

  • Timer

Constructors

Properties

Accessors

Methods

Constructors

Properties

#elapsed: number = 0
#start: number
#stop: number = 0

Accessors

  • get elapsed(): number
  • Gets the elapsed time in milliseconds. If the timer is running, returns the currently elapsed time; otherwise, returns the time elapsed between the start and stop points.

    Returns number

    The elapsed time in milliseconds.

Methods

  • Resets the timer to its initial state. Sets the start time to now, and clears the stop time and elapsed time.

    Returns Timer

    This timer instance, allowing for method chaining

  • Stops the timer if it's running.

    If the timer is already stopped, this method has no effect. When stopped, the elapsed time is updated by adding the time since the timer was started.

    Returns Timer

    The timer instance for method chaining

  • Returns a string representation of the elapsed time.

    Parameters

    • Optional format: "ms" | "seconds" | "minutes"

      The time format to use for the output. - 'ms': milliseconds (default) - 'seconds': seconds with one decimal place - 'minutes': minutes in MM:SS format

    Returns string

    A formatted string representing the elapsed time.