How to Get Engine Current Time in Matter.js
In Matter.js, tracking simulation time is essential for synchronizing animations, triggering physics events, and managing game loops. This article explains how to retrieve the current simulation timestamp directly from the Matter.js engine instance as well as through update event listeners.
Accessing the Timestamp Directly
Matter.js tracks the total elapsed simulation time within the
timing object of an engine instance. You can read the
current time using the engine.timing.timestamp property,
which returns the elapsed simulation time in milliseconds.
// Create an engine
const engine = Matter.Engine.create();
// Retrieve the current simulation time in milliseconds
const currentTime = engine.timing.timestamp;
console.log(`Current Engine Time: ${currentTime} ms`);This value starts at 0 and increases with every
simulation step by the delta time (default is approximately
16.666ms per update for 60 FPS).
Getting the Time via Update Events
If you need the timestamp dynamically on every frame, listen to the
beforeUpdate or afterUpdate events emitted by
the engine. The event object passed to the callback includes the current
timestamp.
Matter.Events.on(engine, 'beforeUpdate', function(event) {
const currentTime = event.timestamp;
console.log(`Frame Timestamp: ${currentTime} ms`);
});Difference Between Engine Time and Real Time
The engine.timing.timestamp represents
simulated time, not real-world wall-clock time. If your
simulation pauses, slows down, or runs at a fixed timestep independent
of the screen refresh rate, engine.timing.timestamp only
reflects the duration the physics world has actually processed. To
record real-world execution time instead, use the standard browser API
performance.now().