So I found this helpful piece of code and used it to provide an instantaneous framerate of some animation I have created. I was hoping someone could help me understand how it functions?
Here is my code:
<script src="jquery.js"></script>
window.countFPS = (function () {
var lastLoop = (new Date()).getMilliseconds();
var count = 1;
var fps = 0;
return function () {
var currentLoop = (new Date()).getMilliseconds();
if (lastLoop > currentLoop) {
fps = count;
count = 1;
} else {
count += 1;
}
lastLoop = currentLoop;
return fps;
};
}());
(function loop() {
requestAnimationFrame(function () {
$('#out').html(countFPS());
loop();
});
}());
The #out
leads to an output tag, if it was not obvious.
the whole magic happens in the requestAnimationFrame, which is an "black box" that really does everything necessary for the function to work. it tells you that "now i have free resources to do a new picture render"
the whole thing just wraps this up and measures the time differences between these moments of "i can render a new frame now" moments. an example: first it was 24th of october, 2015, 10:55:10.1492169, then it was 24th of october, 2015, 10:55:10.1492525. therefore the frequency of being able to draw a new frame is 356 miliseconds. if the cpu were overloaded more, it would be higher
as pointy mentions, it does eat some resources up (but a very negligible pitiful amount of resources) while showing some useful statistics about how often does it have resources to render a new frame - providing a very useful tool to measure effectiveness of currently running scripts