Skip to content

Time and tweens

Updated

Interactive worlds are full of timing: a door that closes after three seconds, a coin that bobs up and down, a slow-motion power-up, a save that waits until the player stops dragging a slider. Scripts have no setTimeout or setInterval. Instead they get delay, debounce and throttle to run code later or less often, Time to measure durations and to slow down, speed up or pause the game, and Tween with Ease to animate any object’s numbers smoothly. Everything a script schedules is tied to it: when the script stops, its timers and tweens stop too.

GlobalWhat it is
TweenAnimate any object's numbers: Tween.to(mesh.position, { x: 5 }, { duration: 1 }), from, value, stop; awaitable.
EaseThe easings, for { ease: Ease.OutCubic }: Linear, and In, Out and InOut of each curve (Quad, Cubic, Quart, Sine, Expo, Back, Elastic, Bounce). In starts slow, Out ends slow, InOut does both; Back overshoots a little, Elastic springs, Bounce bounces. Any function of progress 0..1 works as well.
TimeMeasure with Time.now(), Time.since(start); game time: Time.scale, pause(), resume(), isPaused().
delay
debounce
throttle
  • The update(delta, time) hook runs every frame; delta is the seconds since the last frame. See Lifecycle hooks.
  • await works only inside an async function, such as async function startup().
  • For authored keyframe motion, or the clips inside a model, use an Animation Timeline or an Animation Clip instead of tweens.
  • Moving an entity by writing entity.position differs from calling entity.setPosition. See Working with entities.

MIRA keeps two clocks:

  • Game time is what every frame moves the scene by: physics, animations, components, tweens, delay, debounce, and the delta your update receives. Time.scale speeds it up or slows it down, and Time.pause() stops it.
  • Real time goes on regardless: Time.now(), input, the pointer and the UI, rendering, a headset’s tracking, video, audio and the network.

Rules of game time:

  • Scripts keep running while paused. update is still called, with a delta of 0, so a script can read a key and call Time.resume(). Code that moves things by delta stands still on its own.
  • For this player only. In a multiplayer scene, other players are not paused or slowed.
  • One per app. Every script sees the same Time.scale and pause state. A play session starts at scale 1, not paused; a scene switch keeps both.
  • Physics keeps up to a point. At very high scales, physics falls behind rather than taking ever more steps per frame. A scale of up to about 4 is safe at 60 frames a second.
Member What it does
Time.now() Milliseconds since the page loaded, with fractions. Never goes backwards, ignores changes to the computer’s clock.
Time.since(start) Milliseconds since start, a value from Time.now().
Time.scale How fast game time runs: 1 normal, 0.5 half speed, 2 double. Any number 0 or more; anything else throws a RangeError.
Time.pause() Stops game time. Time.scale is kept.
Time.resume() Carries on after pause(), at Time.scale.
Time.isPaused() Whether game time is stopped.

Use Time.now() to measure durations and Date.now() for the calendar date. To time a frame, use the delta your update hook already receives, in seconds.

Global What it does Returns
delay(fn, ms = 0, ...args) Runs fn(...args) once, ms milliseconds of game time from now. 0 runs it on the next frame. A function that cancels the call if it has not run yet; safe to call twice.
debounce(fn, ms) Makes a version of fn that waits for calls to stop: each call restarts the wait, and fn runs once, ms after the last call, with that call’s arguments. The debounced function, with cancel() to drop a pending run.
throttle(fn, ms) Makes a version of fn that runs at most once every ms. The first call runs at once; calls sooner than ms after the last run are dropped, not queued. The throttled function, which returns true when it ran and false when the call was dropped.
  • Game time. A delay counts the engine’s frames, so it pauses while the game is paused or the browser tab is hidden. It runs on the frame it falls due, before that frame’s update.
  • Cleanup. Pending delays and debounced runs are cancelled when the script stops, so a destroyed object never runs them.
  • Errors. An error thrown, or a promise rejected, in fn goes to the script log.
  • Waiting in an async hook. delay needs a function. To pause inside an async function, wrap it: await new Promise((done) => delay(done, 500)).

When to use which: delay for “do this later”, debounce for “do this once the user stops” (saving, searching), throttle for “do this at most this often” (firing, network updates).

A tween (from “in-between”) animates an object’s numeric properties from their current values to new ones over a set time: a position, a rotation, a scale, a colour’s r, g and b, a material’s opacity, a light’s intensity. A door turns 90 degrees in 0.8 seconds, a pickup bobs up and down, a button grows when clicked. You give the target values and a duration; the tween computes every frame in between. Tweens need no authoring and no components, so they are the quickest way to animate from a script.

Call What it does
Tween.to(target, values, options?) Animates target’s numbers from what they are when it starts to values.
Tween.from(target, values, options?) Animates from values back to what they are now.
Tween.value(start, end, onValue, options?) Animates a plain number, handing each value to onValue(value).
Tween.stop(target) Stops every tween moving target.
Option Default What it sets
duration 1 Seconds it takes. 0 jumps to the end on the next frame.
ease Ease.OutQuad How it speeds up and slows down: one of Ease, or any function of progress from 0 to 1.
delay 0 Seconds to wait before starting.
repeat 0 Times to play again after the first; Infinity for ever.
yoyo false Plays every other repeat backwards.
onUpdate(progress) none Called every frame it moves, with the progress of the current play, 0 to 1.
onComplete() none Called once when it finishes; not when it is stopped.

Each call returns a handle you can control and await:

Member What it is
stop() Stops where it is.
pause(), resume() Holds it where it is; carries on.
isPlaying true until it finishes or is stopped, paused or not.
progress The progress of the current play, 0 to 1. A property, not a method.
await tween Resolves true when it finished, false when it was stopped.
  • Frame timing. Tweens advance before the scripts’ update, so update sees this frame’s values, and tweens pause with the game.
  • Start values are read when a tween starts, after its delay, so a chain of awaits follows on from each step.
  • Newer wins. A new tween on a property another tween is moving takes that property over.
  • Numbers only. Each value must be a finite number, and the target must already have a number under that key, or the call throws. Animate rotation (Euler angles), not a quaternion’s components.
  • Lifetime. A script’s tweens stop when it stops; an await on one then never resumes.
  • Entities. Tweening entity.position writes it directly: it moves what is drawn but sends no Transform events and does not move a physics body. When those matter, tween a value with Tween.value and call setPosition in its callback, or in onUpdate.

An easing curve maps the tween’s linear progress (0 to 1) to a shaped progress, so motion can start gently, stop gently, overshoot or bounce. Ease holds the easing curves: Linear, and the In, Out and InOut forms of Quad, Cubic, Quart, Sine, Expo, Back, Elastic and Bounce (Ease.InQuad, Ease.OutBack, Ease.InOutBounce…).

Family Feel
In… Starts slow, ends fast. Good for things leaving.
Out… Starts fast, ends slow. The most natural for things arriving and coming to rest; OutQuad is the default.
InOut… Slow at both ends. Good for back-and-forth motion, and for doors, cameras, anything that starts and stops at rest.
Quad, Cubic, Quart, Expo Increasingly strong acceleration.
Sine The gentlest curve; ideal for bobbing and breathing.
…Back Overshoots a little, then settles. Lively for pop-ins.
…Elastic Springs past the end and wobbles.
…Bounce Bounces at the end like a dropped ball.

Any function of progress works too: const steps = (t) => Math.floor(t * 4) / 4; moves in four jumps.

A ball that bobs for ever, a box that turns and waits, and a shape that pulses when clicked, all from one script:

animate.jx
#pragma lifecycle(startup)
async function startup() {
const bob = findEntity('Bob');
const turn = findEntity('Turn');
const pulse = findEntity('Pulse');
// Up and down for ever: repeat with yoyo plays every other run backwards.
Tween.to(bob.position, { y: 1.8 }, { duration: 1.2, ease: Ease.InOutSine, repeat: Infinity, yoyo: true });
// Click: grow, then shrink back, one awaited step after the other.
on('pulse/clicked', async (event) => {
if (event.eventType !== EventType.Selectable.Select) return;
// Select fires only on becoming selected: release it so every click counts.
pulse.getComponent(SelectableComponent).setSelected(false);
await Tween.to(pulse.scale, { x: 1.5, y: 1.5, z: 1.5 }, { duration: 0.25, ease: Ease.OutBack });
await Tween.to(pulse.scale, { x: 1, y: 1, z: 1 }, { duration: 0.4 });
log('Pulsed');
});
// A quarter turn, a pause, and again.
for (;;) {
await Tween.to(turn.rotation, { y: turn.rotation.y + Math.PI / 2 }, { duration: 0.8, ease: Ease.InOutCubic });
if (!(await Tween.value(0, 1, () => {}, { duration: 0.6 }))) return;
}
}
  • startup is async, so it can await tweens. The engine does not wait for it; the endless loop at the end runs alongside everything else.
  • The bob tween never ends: repeat: Infinity with yoyo: true goes up and down for ever, and Ease.InOutSine makes the turnarounds soft.
  • The click handler is itself async: each await waits for one step, so the shape grows, then shrinks, then logs.
  • The loop turns the box by a quarter turn, reading turn.rotation.y afresh each time. Tween.value(0, 1, () => {}, …) is used as a 0.6 second wait; it resolves false if it was stopped (for example when the script is released), and the loop then ends.

A pickup that floats gently for ever.

Bob.jx
#pragma slot(ref=height, type=Number, min=0, max=2, default=0.2)
#pragma slot(ref=seconds, type=Number, min=0.1, max=10, default=1.2)
#pragma lifecycle(startup)
function startup() {
const target = self.parent;
Tween.to(target.position, { y: target.position.y + height }, {
duration: seconds,
ease: Ease.InOutSine,
repeat: Infinity,
yoyo: true,
});
}

How it works

  • Tween.to animates position.y from where it is to height higher.
  • repeat: Infinity plays it for ever, and yoyo: true plays every other run backwards, so it goes up and down.
  • Ease.InOutSine slows at both ends for a soft float.
  • The tween stops by itself when the script stops.

A collectible bobs gently; when a pickup/taken signal arrives, it stops bobbing, shrinks away and removes itself.

Pickup.jx
#pragma lifecycle(startup)
async function startup() {
const start = self.parent.position.y;
Tween.to(self.parent.position, { y: start + 0.2 }, { ease: Ease.InOutSine, repeat: Infinity, yoyo: true });
Tween.to(self.parent.rotation, { y: M_TAU }, { duration: 3, ease: Ease.Linear, repeat: Infinity });
on('pickup/taken', async () => {
Tween.stop(self.parent.position);
Tween.stop(self.parent.rotation);
await Tween.to(self.parent.scale, { x: 0, y: 0, z: 0 }, { duration: 0.3, ease: Ease.InBack });
destroy(self.parent);
});
}
  • The bob rises 0.2 m over the default one second and comes back, for ever.
  • The spin turns a full circle (M_TAU, 2π radians) in 3 seconds with Ease.Linear, so it never slows down. With repeat, each run starts again from where the tween first started, giving a continuous rotation.
  • Tween.stop takes the object being animated and stops every tween on it.
  • Ease.InBack pulls back slightly before shrinking, a small anticipation that reads well.
  • destroy runs only after the shrink finishes, because the handler awaits the tween.

Open a door on a signal, wait, then close it, with each step awaited.

AutoDoor.jx
#pragma slot(ref=holdSeconds, type=Number, min=0, max=30, default=3)
#pragma lifecycle(startup)
let door = null;
let busy = false;
function wait(ms) {
return new Promise((done) => delay(done, ms));
}
async function cycle() {
if (busy) return;
busy = true;
await Tween.to(door.rotation, { y: Math.PI / 2 }, { duration: 0.8, ease: Ease.InOutCubic });
await wait(holdSeconds * 1000);
await Tween.to(door.rotation, { y: 0 }, { duration: 0.8, ease: Ease.InOutCubic });
busy = false;
}
function startup() {
door = findEntity('Door');
on('door/open', cycle);
}

How it works

  • wait wraps delay in a promise, so an async function can pause for a while.
  • Each await waits for one step to finish before starting the next.
  • The busy flag ignores new requests while a cycle runs.
  • If the script stops mid-cycle, its tweens and delay are cancelled and the await never resumes, so no code runs against a removed door.

A power-up that slows the game, and a key that pauses and resumes. Time controls game time for every script and component at once.

TimeControl.jx
#pragma lifecycle(startup, update)
let cancelSlowMo;
function startup() {
on('powerup/slow-motion', () => {
cancelSlowMo?.();
Time.scale = 0.3;
cancelSlowMo = delay(() => (Time.scale = 1), 1500);
});
}
function update() {
if (!Input.keyboard.isKeyReleased(Key.Escape)) return;
if (Time.isPaused()) {
Time.resume();
log('Resumed');
} else {
Time.pause();
log('Paused');
}
}
  • Setting Time.scale to 0.3 slows physics, animations, tweens and update(dt) to 30 percent.
  • delay counts game time, so at a scale of 0.3 its 1500 milliseconds last 5 real seconds: a long, dramatic slow motion. Calling the previous cancel function first means a second power-up restarts the timer instead of ending the first one early.
  • Escape toggles the pause. update still runs while paused (with dt 0), which is why the script can resume.
  • isKeyReleased fires once per press, so one press toggles once.

Throttle a weapon, debounce a slider, and time a heavy job, in one script.

Timing.jx
#pragma lifecycle(startup, update)
const fire = throttle(() => {
spawn('Bullet', { position: self.parent.position, enabled: true });
}, 250);
const saveVolume = debounce((value) => {
emit('settings/save', { volume: value });
log('Saved volume', value);
}, 400);
function rebuildGrid() {
const start = Time.now();
for (let i = 0; i < 100000; i++) Math.sqrt(i);
log(`Grid rebuilt in ${Time.since(start).toFixed(2)} ms`);
}
function startup() {
on('volume', (event) => {
if (event.eventType === EventType.UISlider.Change) saveVolume(event.data.value);
});
rebuildGrid();
}
function update() {
if (Input.keyboard.isKeyPressed(Key.Space)) fire();
}

How it works

  • fire runs at most four times a second however long Space is held; extra calls are dropped.
  • While the player drags a slider, saveVolume is called many times, but it runs once, 400 ms after the last change.
  • Time.now() and Time.since() measure real elapsed milliseconds, unaffected by Time.scale.
  • The Bullet entity is a disabled template copied with spawn. See Scene and entities.

Tweening position directly does not move a physics body. For a platform with a kinematic body, tween a plain number and apply it with setPosition.

Lift.jx
#pragma lifecycle(startup)
let travel;
async function startup() {
const lift = self.parent;
const x = lift.position.x;
const z = lift.position.z;
const bottom = lift.position.y;
on('lift/call', async (floorHeight) => {
travel?.stop();
travel = Tween.value(lift.position.y, bottom + floorHeight, (y) => lift.setPosition(x, y, z), {
duration: 2,
ease: Ease.InOutQuad,
});
if (await travel) emit('lift/arrived', floorHeight);
});
}
  • Tween.value animates a number and hands each value to the callback, which calls setPosition. That keeps the physics body and Transform events in step.
  • A new call stops the previous trip with travel?.stop() and starts from the current height, so the lift can change direction smoothly.
  • await travel resolves true only when the trip completed, so lift/arrived is not sent for an interrupted trip.
  • emit('lift/call', 4) from a button script sends the lift to 4 m above its start.

Time.now() and Time.since() are a precise stopwatch in real time.

Stopwatch.jx
#pragma lifecycle(startup)
function startup() {
let started;
on('race/start', () => {
started = Time.now();
});
on('race/finish', () => {
if (started === undefined) return;
const seconds = Time.since(started) / 1000;
log(`Finished in ${seconds.toFixed(2)} s`);
started = undefined;
});
}
  • Time.now() returns milliseconds with fractions and never goes backwards, even if the computer’s clock changes.
  • Time.since(started) is the elapsed real time; divide by 1000 for seconds.
  • Because Time.now() is real time, the stopwatch keeps counting during slow motion and pauses. For game time, add up dt in update instead.
Wrong
async function startup() {
await delay(500); // throws a TypeError: delay needs a function
}
Right
async function startup() {
await new Promise((done) => delay(done, 500));
}
Wrong
#pragma lifecycle(startup)
function startup() {
await Tween.to(self.parent.scale, { x: 2, y: 2, z: 2 }); // does not compile
}
Right
#pragma lifecycle(startup)
async function startup() {
await Tween.to(self.parent.scale, { x: 2, y: 2, z: 2 });
}

Tweens animate numbers only. Animate rotation (an Euler), not quaternion.

Wrong
Tween.to(box.quaternion, { y: 0.7 }); // breaks the rotation
Right
Tween.to(box.rotation, { y: Math.PI / 2 });
Wrong
log(tween.progress()); // TypeError: progress is not a function
Right
log(tween.progress);

Tweening crate.position moves the drawing but leaves its body and colliders behind. Tween a plain value and place the entity with its setter:

Right
const startY = crate.position.y;
Tween.value(startY, startY + 2, (y) => crate.setPosition(crate.position.x, y, crate.position.z), { duration: 1 });
Wrong
function update() {
self.parent.rotation.y += 0.02; // faster on faster screens, ignores pause
}
Right
function update(dt) {
self.parent.rotation.y += 1.2 * dt; // 1.2 radians a second, stops when paused
}

onComplete runs only when a tween finishes. Check the awaited result instead: false means stopped.

Each call replaces the last on the same property and restarts the motion. Start tweens from events or startup, not from update.

Time.pause() stops game time for every script; read input in update to resume.