I’m adding menu states to an interactive canvas animation based on my edits to this MDN exercise. I want to pause the animation when I press esc (not hide it under an opaque overlay) and resume when I click “return”. At this point I feel like I don’t know enough JS to implement it, or whether it’s possible in JS.
(As you can see, I’m a beginner and this is for me to practice simple JS and CSS, not make a proper browser game, so “real world” solutions are not the focus)
The pause menu opens and closes as intended, but I don’t know how to implement the actual pause!
I tried do { } while (clicked === false);
and the page froze. I looked it up and learned that waiting and blocking is different, and that you should never do this. I found out about async/await and understood some simple examples. But I didn’t figure out how to apply that to functions in my code. I haven’t gotten to the asynchronous JS part of my coding course yet and it really confuses me. Do I need to learn about asyncronous JS first to solve this? Some replies to similar questions sound like in JS you’re not supposed to pause code execution that way at all… I have no idea how to approach this anymore.
In the MRE snippet I’ve removed unrelated elements and styling, and replaced the canvas with a random number generator.
// pause-test.js
let testArea = document.getElementById("test-area");
let pauseScreen = document.getElementById("pause-menu");
let resumeButton = document.getElementById("resume-button");
function random(min, max) {
return Math.round(min + ((max - min) * Math.random()));
}
function idleMode() {
// removed canvas and shapes declarations
// draw(shapes);
draw();
// esc should open pause menu
document.addEventListener("keydown", (event) => {
if ((event.key === "Escape")) {
console.log("esc in animation()");
pauseMenu();
}
})
}
idleMode();
function draw() {
function loop() {
// removed frame drawing functions
// instead display a random number every second
let num = random(0, 10000000);
testArea.textContent = `${num}`;
setTimeout(() => {
requestAnimationFrame(loop);
}, 1000);
return;
}
loop();
}
function pauseMenu() {
// absolute positioned on top of the canvas
pauseScreen.classList.remove("hide");
console.log("paused");
// QUESTION: How to pause animation until this event fires?
resumeButton.addEventListener("click", pauseResume);
return;
}
function pauseResume() {
console.log("unpaused");
pauseScreen.classList.add("hide");
return;
}
<main>
<div class="display">
<p id="test-area">test area</p>
<!-- <canvas tabindex='1'></canvas> -->
<section id="pause-menu" class="hide">
<header>Paused</header>
<button id="resume-button">resume</button>
<!-- <button id="exit-button">exit</button> -->
</section>
</div>
</main>