From bc57e7c2caf32a967ae7dcd4d1769c96acb51a77 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Matt=C3=A9o=20Delabre?= Date: Mon, 4 May 2020 18:37:33 +0200 Subject: [PATCH] Stop simulation when page is hidden --- index.mjs | 30 +++++++++++++++++++++++++++++- 1 file changed, 29 insertions(+), 1 deletion(-) diff --git a/index.mjs b/index.mjs index 4baf758..882b24e 100644 --- a/index.mjs +++ b/index.mjs @@ -45,6 +45,7 @@ for (let i = 0; i < 300; ++i) }); } +let paused = false; let lastTime = null; const loop = time => @@ -60,7 +61,34 @@ const loop = time => boids.update(activeBoids, params, delta); draw.fill(activeBoids, params, boidsCtx, width, height, center); + if (!paused) + { + requestAnimationFrame(loop); + } +}; + +const start = () => +{ + lastTime = null; + paused = false; requestAnimationFrame(loop); }; -requestAnimationFrame(loop); +const pause = () => +{ + paused = true; +}; + +document.onvisibilitychange = () => +{ + if (document.visibilityState === 'visible') + { + start(); + } + else + { + pause(); + } +}; + +start();