time-machine-js
v1.1.0
Published
A zero-dependency utility to monkey-patch Date.now() globally.
Maintainers
Readme
time-machine-js
A zero-dependency, framework-agnostic utility that monkey-patches Date.now() globally to simulate a different point in time. Works identically in browser and Node.js environments.
Features
- Zero dependencies: No external dependencies required.
- Framework agnostic: Use it with React, Vue, Vanilla JS, or Node.js.
- Global patch: Affects
Date.now()globally, ensuringnew Date()and other time-dependent utilities work as expected. - Dual Exports: Ships with both ESM and CJS support.
- TypeScript: Fully typed with included definitions.
Installation
npm install time-machine-jsAPI
The core API consists of five main functions:
travel(timestamp: number, mode: 'flowing' | 'frozen'): void
Moves the environment time to the specified Unix timestamp.
flowing: Time continues to advance normally from the specified point.frozen: Time remains fixed at the specify timestamp.
returnToPresent(): void
Restores the original Date.now and clears internal state.
getOffset(): number | null
Returns the current offset in ms (flowing mode) or the frozen timestamp (frozen mode). Returns null if inactive.
isActive(): boolean
Returns true if the time machine is currently active.
getMode(): 'flowing' | 'frozen' | null
Returns the current mode of the time machine, or null if inactive.
Persistence (Browser Only)
For environments with localStorage, you can manually save and restore the time machine state across page reloads:
save(storageKey?: string): void
Writes the current mode and offset/timestamp to localStorage. Defaults to __timeMachine__.
restore(storageKey?: string): boolean
Reads the state from localStorage and activates it. Returns true if a state was found and applied.
Usage
Basic Example
import { travel, returnToPresent } from 'time-machine-js';
// Travel to Jan 1st, 2025
travel(new Date('2025-01-01').getTime(), 'frozen');
console.log(new Date().toISOString()); // 2025-01-01T00:00:00.000Z
returnToPresent();
console.log(new Date().getFullYear()); // Current yearPersistence
import { restore, save, travel } from 'time-machine-js';
// On app initialization
restore();
// Later
travel(Date.now() + 3600000, 'flowing');
save();Caveats
new Date()
In most modern JavaScript environments (V8, Node.js), the Date constructor uses Date.now() internally to determine the current time. This means monkey-patching Date.now() is sufficient to "travel" for both Date.now() and new Date().
performance.now()
performance.now() is not patched by this utility, as it represents a monotonic clock used for high-resolution profiling rather than wall-clock time.
License
MIT
