Skip to content

Instantly share code, notes, and snippets.

@greggman
Created August 5, 2015 16:29
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save greggman/b15e4812b2d444966239 to your computer and use it in GitHub Desktop.
Save greggman/b15e4812b2d444966239 to your computer and use it in GitHub Desktop.
RAF with pause on blur
// To use call
//
// run(mainLoopFn);
//
// Where mainLoopFn is a function you want to be called every frame
function run(fn) {
var requestId;
function requestLoop(result) {
requestId = result ? undefined : requestAnimationFrame(loop);
}
function loop(time) {
var result = fn(time);
requestLoop(result);
}
var start = function() {
if (requestId === undefined) {
requestLoop(false);
}
};
var stop = function() {
if (requestId !== undefined) {
cancelAnimationFrame(requestId);
requestId = undefined;
}
};
// The only reason this is here is because when you
// open devtools in Chrome the game blurs. As the
// devtools is expanded and contracted, if the game
// is not running it won't respond to being resized.
var updateOnce = function() {
if (requestId === undefined) {
start();
stop();
}
};
// This is here because running a game at 60fps
// in my MacBook Pro switches the discrete GPU
// and uses a ton of CPU as well, eating up my
// battery. So, if I'm running locally I make
// the game pause on blur which means effectively
// it will stop anytime I switch back to my editor.
window.addEventListener('blur', stop, false);
window.addEventListener('focus', start, false);
window.addEventListener('resize', updateOnce, false);
start();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment