Skip to content

@web-engine-dev/time

Time management, fixed timestep, and timers for web-engine-dev. Provides comprehensive time management including delta time tracking, fixed timestep simulation, and timer utilities.

Features

  • Delta Time Tracking: Frame-by-frame time measurement
  • Fixed Timestep: Deterministic physics simulation
  • Time Scaling: Slow motion, pause, fast forward
  • Timers: Countdown timers with callbacks
  • Stopwatch: Elapsed time measurement

Installation

bash
npm install @web-engine-dev/time
# or
pnpm add @web-engine-dev/time

Quick Start

typescript
import { createTimeManager } from '@web-engine-dev/time';

const time = createTimeManager({
  fixedTime: { timestep: 1 / 60 },
  maxDelta: 0.1,
});

function gameLoop(timestamp: number) {
  time.update(timestamp);

  // Variable update (rendering)
  render(time.time.delta);

  // Fixed update (physics)
  while (time.shouldFixedUpdate()) {
    physicsStep(time.fixedTime.timestep);
    time.consumeFixedStep();
  }

  requestAnimationFrame(gameLoop);
}

API Reference

Time State

PropertyDescription
deltaDelta time in seconds
deltaMsDelta time in milliseconds
elapsedTotal elapsed time in seconds
elapsedMsTotal elapsed time in milliseconds
frameCurrent frame number
timeScaleTime multiplier (1.0 = normal)
scaledDeltaDelta time × timeScale

Fixed Time State

PropertyDescription
timestepFixed timestep duration
accumulatorAccumulated time for fixed updates
stepsThisFrameNumber of fixed steps this frame
alphaInterpolation factor (0-1)

TimeManager Methods

MethodDescription
update(timestamp)Update time for new frame
shouldFixedUpdate()Check if fixed update needed
consumeFixedStep()Consume one fixed timestep
setTimeScale(scale)Set time multiplier
pause()Pause time (scale = 0)
resume()Resume previous scale
isPaused()Check if paused

Timers

typescript
// Create a timer
const timer = time.createTimer({
  duration: 5, // 5 seconds
  repeating: false,
  onComplete: () => console.log('Timer done!'),
  onTick: (t) => console.log(t.progress),
});

// Update timers each frame
time.updateTimers(time.time.delta);

// Query timer state
timer.progress; // 0-1
timer.remaining; // Seconds left
timer.finished; // Boolean

Stopwatch

typescript
const stopwatch = time.createStopwatch();

stopwatch.start();
// ... do work ...
stopwatch.stop();

console.log(stopwatch.elapsedSeconds());
stopwatch.reset();

Time Scaling

typescript
// Slow motion
time.setTimeScale(0.5);

// Fast forward
time.setTimeScale(2.0);

// Pause
time.pause();

// Resume
time.resume();

Proprietary software. All rights reserved.