@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/timeQuick 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
| Property | Description |
|---|---|
delta | Delta time in seconds |
deltaMs | Delta time in milliseconds |
elapsed | Total elapsed time in seconds |
elapsedMs | Total elapsed time in milliseconds |
frame | Current frame number |
timeScale | Time multiplier (1.0 = normal) |
scaledDelta | Delta time × timeScale |
Fixed Time State
| Property | Description |
|---|---|
timestep | Fixed timestep duration |
accumulator | Accumulated time for fixed updates |
stepsThisFrame | Number of fixed steps this frame |
alpha | Interpolation factor (0-1) |
TimeManager Methods
| Method | Description |
|---|---|
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; // BooleanStopwatch
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();