This code will draw/loop as fast as possible
function loop() {
draw();
loop();
}
This code will artificially add ~100 ms of time to each loop cycle
function loop() {
draw();
setTimeout(loop, 100);
}
Something I use when I create loops like this is a delta so accurate calculations can be made
function draw(delta) {
console.log("%f ms", delta);
}
function loop(last) {
var now = performance.now();
var delta = now - last;
draw(delta);
setTimeout(function() { loop(now); }, 100);
}
loop(0);
// 102.51500000001397 ms
// 102.38000000000466 ms
// 105.33499999996275 ms
// 101.27500000002328 ms
// 103 ms
// 100.88000000000466 ms
// 100.9649999999674 ms
// 100.69500000000698 ms
// 102.01500000001397 ms
// 105.85499999998137 ms
As you can see, draw is being called about once every 100 ms. This is approximately 10 frames per second. You can now use this delta to do precise calculations for things like animation sequences or positioning moving elements
You could easily make this a variable for your loop
function framesPerSecond(x) {
return 1e3/x;
}
function draw(delta) {
console.log("%f ms", delta);
}
function loop(fps, last) {
var now = performance.now();
var delta = now - last;
draw(delta);
setTimeout(function() { loop(fps, now); }, fps);
}
loop(framesPerSecond(25), 0); // 25 frames per second
// 42.8150000000023 ms
// 42.1600000000035 ms
// 44.8150000000023 ms
// 41.8299999999872 ms
// 43.195000000007 ms
// 41.7250000000058 ms
// 42.1349999999802 ms
// 43.0950000000012 ms
You can simulate any frame rate pretty easily now
loop(framesPerSecond(0.5), 0); // 1 frame per 2 seconds
// 2001.58 ms
// 2002.705 ms
// 2005.9 ms
// 2001.665 ms
// 2002.59 ms
// 2006.165 ms
Note: framesPerSecond
will not be very accurate when draw
takes any significant amount of time to complete. You could improve this by measuring the duration it takes for draw
to run each cycle and subtracting that from the fps
delay.