The native runtime for three.js: three.js, down to the metal. 45× smaller than Electron, on a Sony PS3, and path-traced at 60 fps on ray-tracing GPUs.
Rust electron-alternativegame-engineglobal-illuminationgraphicsjavascript-runtimemetalpath-tracingray-tracingreal-time-renderingrenderingrustthreejstypescriptvoxelvulkanwebgpuwgpu
// Timers and animation frames. The host wakes the page at the earliest deadline (`__native.sys.wakeAt`)
// and calls `runTimers(now)`; frames arrive through `runFrame(now)` while callbacks are pending.
import { reportError } from "./events.ts";
const sys = __native.sys;
interface Timer { id: number; at: number; fn: any; args: any[]; every: number }
const timers = new Map<number, Timer>();
let nextId = 1;
let scheduled = Infinity;
function reschedule() {
let min = Infinity;
for (const t of timers.values()) if (t.at < min) min = t.at;
if (min !== scheduled) { scheduled = min; sys.wakeAt(min); }
}
function addTimer(fn: any, ms: any, args: any[], repeat: boolean) {
const id = nextId++;
const delay = Math.max(0, Number(ms) || 0);
timers.set(id, { id, at: sys.now() + delay, fn, args, every: repeat ? Math.max(delay, 1) : 0 });
reschedule();
return id;
}
export function setTimeout(fn: any, ms?: any, ...args: any[]) { return addTimer(fn, ms, args, false); }
export function setInterval(fn: any, ms?: any, ...args: any[]) { return addTimer(fn, ms, args, true); }
export function clearTimeout(id: any) { if (timers.delete(Number(id))) reschedule(); }
export const clearInterval = clearTimeout;
export function runTimers(now: number) {
scheduled = Infinity;
// Fire in deadline order; timers added while running wait for the next wake.
const due = [...timers.values()].filter((t) => t.at <= now + 0.5).sort((a, b) => a.at - b.at || a.id - b.id);
for (const t of due) {
if (!timers.has(t.id)) continue;
if (t.every) t.at = Math.max(t.at + t.every, now); else timers.delete(t.id);
try {
if (typeof t.fn === "function") t.fn(...t.args);
else if (typeof t.fn === "string") (0, eval)(t.fn);
} catch (e) { reportError(e); }
}
reschedule();
}
let frameCallbacks = new Map<number, FrameRequestCallback>();
let nextFrameId = 1;
export function requestAnimationFrame(cb: FrameRequestCallback) {
const id = nextFrameId++;
frameCallbacks.set(id, cb);
sys.requestFrame();
return id;
}
export function cancelAnimationFrame(id: number) { frameCallbacks.delete(id); }
const frameHooks: ((now: number) => void)[] = [];
/** Runtime modules that need a turn every frame after the page's callbacks (DOM commit …). */
export function onFrameEnd(f: (now: number) => void) { frameHooks.push(f); }
export function runFrame(now: number) {
const cbs = frameCallbacks;
frameCallbacks = new Map();
for (const cb of cbs.values()) {
try { cb(now); } catch (e) { reportError(e); }
}
for (const h of frameHooks) {
try { h(now); } catch (e) { reportError(e); }
}
}
export function queueMicrotask(fn: () => void) {
Promise.resolve().then(() => { try { fn(); } catch (e) { reportError(e); } });
}