High-precision timer class providing microsecond-level timing functionality. This class wraps native precision timer functionality for accurate task scheduling.

  1. Basic single-shot timer

    const timer = new PrecisionTimer('my-timer')
    timer.create()

    // Add a task that runs once after 1000000 microseconds (1 second)
    const taskId = timer.addTask(1000000, 0, () => {
    console.log('Timer fired after 1 second!')
    })
  2. Recurring timer

    // Add a task that runs every 500000 microseconds (500ms)
    const taskId = timer.addTask(500000, 500000, () => {
    console.log('This runs every 500ms')
    })

    // Later, cancel the recurring task
    timer.cancelTask(taskId)
  3. High-precision timing measurement

    // Get current high-precision timestamp
    const startTime = PrecisionTimer.getCurrentTimestamp()

    // Add a task with microsecond precision (100 microseconds delay)
    timer.addTask(100, 0, () => {
    const endTime = PrecisionTimer.getCurrentTimestamp()
    console.log(`Elapsed: ${endTime - startTime} microseconds`)
    })

Constructors

  • Creates a new PrecisionTimer instance

    Parameters

    • name: string

      Unique name identifier for this timer instance

    Returns PrecisionTimer

Methods

  • Adds a new timer task with microsecond precision.

    Parameters

    • delayMicrosec: number

      Initial delay before first execution in microseconds

    • intervalMicrosec: number = 0

      Interval between recurring executions in microseconds (0 for single execution)

    • callback: () => void

      Function to execute when timer fires

    Returns number

    Task ID that can be used to cancel the task

    If timer is not created

    // Single execution after 1 second
    const taskId = timer.addTask(1000000, 0, () => console.log('Done!'))

    // Recurring execution every 500ms
    const intervalId = timer.addTask(500000, 500000, () => console.log('Tick'))
  • Internal

    Internal callback handler for timer tasks

    Parameters

    • task: TimerTask

      Timer task information containing taskId and triggerTime

    Returns void

  • Cancels a previously scheduled timer task.

    Parameters

    • taskId: number

      The task ID returned by addTask()

    Returns boolean

    True if task was successfully cancelled, false if task was not found

    If timer is not created

  • Creates and initializes the precision timer. Must be called before adding any tasks.

    Returns void

    If timer creation fails

  • Destroys the timer and cancels all pending tasks. After calling this method, the timer cannot be used until create() is called again.

    Returns void

    must call this method before the process exits,

    Util.End(()=>{
    timer.destroy()
    })