Skip to content

Instantly share code, notes, and snippets.

@kidGodzilla
Created August 4, 2016 01:48
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 kidGodzilla/0254006d5fa37a5efdbe67abbcbe0a0f to your computer and use it in GitHub Desktop.
Save kidGodzilla/0254006d5fa37a5efdbe67abbcbe0a0f to your computer and use it in GitHub Desktop.
Using requestAnimationFrame() for performance checking
/**
* Performance Checking
*
* Will enable and disable a flag on the window object
* When Javascript performance suffers, so that optional features
* Can be Disabled or delayed
*/
(function () {
var lastTimestamp = + new Date();
/**
* Compares the execution of requestAnimationFrame to it's ideal, 60fps.
* When Javascript is performant, the difference should approach 16ms.
* When experiencing degraded Javascript performance, this value will begin to increase.
* If it reaches 32, we toggle the flag `window.performant`, which other
* functions can use to turn off the execution of optional features
*/
function perfCheck () {
var difference = + new Date() - lastTimestamp;
lastTimestamp = + new Date();
if (difference > 32) {
window.performant = false;
} else {
window.performant = true;
}
requestAnimationFrame(perfCheck);
}
requestAnimationFrame(perfCheck);
})();
/**
* Deferred Execution
*/
var deferredExecutionTimers = window.deferredExecutionTimers = {};
function s4 () {
return Math.floor((1 + Math.random()) * 0x10000).toString(16).substring(1);
}
function deferExecution (condition, callback, interval) {
if (!deferredExecutionTimers) window.deferredExecutionTimers = {};
// Generate a new UUID to track this timer
var uuid = s4() + s4() + s4();
interval = interval || 1000;
deferredExecutionTimers[uuid] = setInterval(function () {
if (condition && typeof(condition) === "function") condition = condition();
if (condition) {
if (callback && typeof(callback) === "function") callback();
clearTimeout(deferredExecutionTimers[uuid]);
}
}, interval);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment