Created
April 9, 2021 00:15
-
-
Save spite/b717794dc383bac91d856ad8d723e861 to your computer and use it in GitHub Desktop.
Full Unthrottle
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Keep the tab busy with audio. | |
const audioCtx = new AudioContext(); | |
const gainNode = audioCtx.createGain(); | |
gainNode.gain.value = 0.1; | |
gainNode.connect(audioCtx.destination); | |
const oscillatorNode = audioCtx.createOscillator(); | |
oscillatorNode.type = "square"; | |
oscillatorNode.frequency.setValueAtTime(0.00001, audioCtx.currentTime); | |
oscillatorNode.connect(gainNode); | |
oscillatorNode.start(); | |
// Hook rAF. | |
const origRequestAnimationFrame = requestAnimationFrame; | |
let timeoutID; | |
let rafID; | |
requestAnimationFrame = (c) => { | |
// If page is hidden, use a timer. | |
// Otherwise, use rAF. | |
if (document.hidden) { | |
timeoutID = setTimeout(c, 1); | |
} else { | |
rafID = origRequestAnimationFrame(c); | |
} | |
}; | |
// Handle page visibility changes. | |
document.addEventListener("visibilitychange", handleVisibilityChange, false); | |
function handleVisibilityChange(e) { | |
// If page is hidden, cancel the rAF. | |
// Otherwise, cancel the timer. | |
if (document.hidden) { | |
if (rafID) { | |
rafID = cancelAnimationFrame(rafID); | |
} | |
animate(); | |
} else { | |
if (timeoutID) { | |
timeoutID = clearTimeout(timeoutID); | |
} | |
animate(); | |
} | |
} | |
// Yield to the Autoplay policy. | |
window.addEventListener( | |
"click", | |
() => { | |
audioCtx.resume(); | |
}, { | |
once: true | |
} | |
); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
animate
is my function that steps, renders, and callsrequestAnimationFrame
:YMMV