ditch setTimeout

This commit is contained in:
David Vanderson 2022-06-10 08:15:32 -04:00 committed by Stephen Gutekanst
parent 4eb872944a
commit ade26b24b1
2 changed files with 6 additions and 28 deletions

View file

@ -140,9 +140,7 @@ const mach = {
observer: undefined,
events: [],
changes: [],
update: undefined,
wait_event_timeout: 0,
wait_event_timer: undefined,
init(wasm) {
this.wasm = wasm;
@ -184,14 +182,6 @@ const mach = {
throw Error(mach.getString(str, len));
},
machClearEventTimer() {
if (mach.wait_event_timer !== undefined) {
clearTimeout(mach.wait_event_timer);
mach.wait_event_timer = undefined;
window.requestAnimationFrame(mach.update);
}
},
machCanvasInit(width, height, id) {
let canvas = document.createElement("canvas");
canvas.id = "#mach-canvas-" + mach.canvases.length;
@ -209,39 +199,32 @@ const mach = {
canvas.addEventListener("keydown", (ev) => {
mach.events.push(...[1, convertKeyCode(ev.code)]);
mach.machClearEventTimer();
});
canvas.addEventListener("keyup", (ev) => {
mach.events.push(...[2, convertKeyCode(ev.code)]);
mach.machClearEventTimer();
});
canvas.addEventListener("mousemove", (ev) => {
mach.events.push(...[3, ev.clientX, ev.clientY]);
mach.machClearEventTimer();
});
canvas.addEventListener("mousedown", (ev) => {
mach.events.push(...[4, ev.button]);
mach.machClearEventTimer();
});
canvas.addEventListener("mouseup", (ev) => {
mach.events.push(...[5, ev.button]);
mach.machClearEventTimer();
});
canvas.addEventListener("wheel", (ev) => {
mach.events.push(...[6, ev.deltaX, ev.deltaY]);
mach.machClearEventTimer();
});
canvas.addEventListener("mach-canvas-resize", (ev) => {
const cv_index = mach.canvases.findIndex((el) => el.canvas === ev.currentTarget);
const cv = mach.canvases[cv_index];
mach.changes.push(...[1, cv.canvas.width, cv.canvas.height, window.devicePixelRatio]);
mach.machClearEventTimer();
});
document.body.appendChild(canvas);

View file

@ -25,22 +25,17 @@
instance.exports.wasmInit();
let frame = true;
let last_update_time = performance.now();
let update = function() {{
if (!frame) return;
instance.exports.wasmUpdate();
if (mach.wait_event_timeout > 0) {{
mach.wait_event_timer = setTimeout(() => {{
window.requestAnimationFrame(update);
}},
mach.wait_event_timeout * 1000);
}}
else {{
window.requestAnimationFrame(update);
if (mach.machHasEvent() ||
(last_update_time + (mach.wait_event_timeout * 1000)) <= performance.now()) {{
instance.exports.wasmUpdate();
last_update_time = performance.now();
}}
window.requestAnimationFrame(update);
}};
mach.update = update;
window.requestAnimationFrame(update);
window.addEventListener("mach-close", () => {{