When using requestAnimationFrame, how to make part of animation update faster - javascript

I am using requestAnimationFrame to make a game (game like a snake), and the frame update speed of the game is initially updated each second one time
It needs to update the "requestAnimationFrame" of this snake from a second each time to 0.5 second each time. Because of many snakes’ design and while a snake touches any item, it will get a speed-up situation for 10 seconds.
My question is how to maintain the main "requestAnimationFrame" (updated every second), and there is still another "requestAnimationFrame" (updated every 0.5 second)?
main requestAnimationFrame code
let speed = 1;
let lastRenderTime = 0;
const doAnimation = function (currentTime) {
window.requestAnimationFrame(doAnimation);
const secondRender = (currentTime - lastRenderTime) / 1000; // secondRender is used to control the update per second
if (secondRender < 1 / speed) {
return;
}
lastRenderTime = currentTime
}
window.requestAnimationFrame(doAnimation);

requestAnimationFrame fire rate is usually around 60Hz. That is 60 calls per second, giving you a maximum theoretical precision of ~16ms (0.016s).
This means that inside you loop you can make things update at any rate above that. But why would you like to truncate precision?
The whole point of requestAnimationFrame is to know exactly when a repaint will happen and to pass information about your animation at the right time. As an example: if your snake has to move 1000px every second, why would you notify the browser about the update every second? Ideally you should update your view on every frame. So in this example, a 16px variation every 16ms.
Please see the following snippet and note that there are no conditionals, anywhere. But just continuous update.
Obviously final implementation would depend on your use case, but this is only the working principle.
const boxA = document.getElementById('boxA'); // DEMO
const boxB = document.getElementById('boxB'); // DEMO
let xA = 0; // DEMO
let xB = 0; // DEMO
const speedA = 80; // [px/s]
const speedB = 160; // [px/s]
let then = 0;
const animate = function (now) {
window.requestAnimationFrame(animate);
const delta = (now - then) / 1000;
// A
const a = speedA * delta;
boxA.style.transform = `translateX(${xA += a}px)`; // DEMO
// B
const b = speedB * delta;
boxB.style.transform = `translateX(${xB += b}px)`; // DEMO
then = now
}
window.requestAnimationFrame(animate);
.container {
display: flex;
flex-direction: column;
}
#boxA,
#boxB {
display: inline-block;
height: 50px;
width: 50px;
transform: translateX(0);
}
#boxA {
background-color: #ff0000;
}
#boxB {
background-color: #0000ff;
}
<div class='container'>
<span id='boxA'></span>
<span id='boxB'></span>
</div>

let then, then2;
(function loop(delta) {
then = then || delta;
then2 = then2 || delta;
let time = delta - then;
let time2 = delta - then2;
if (time > 1000) {
then = delta;
// in here every second
}
if (time2 > 500) {
then2 = delta;
// in here every 0.5 seconds
}
document.body.innerHTML = time.toFixed(2) + '<br>' + time2.toFixed(2);
requestAnimationFrame(loop);
})();

Related

JavaScript stopwatch being slower than expected

In my quest to become a JavaScript developer and as an F1 fan, I had to make a stopwatch, to track reaction time. The problem I stumbled upon, and it seems to be the case in many tutorials I've seen, is that you can't really be millisecond exact.
What I mean is, when I try to set an Interval for every 10 milliseconds, it works perfectly, but if I try to set an Interval for 1 millisecond, 1 second on my page is like 5 seconds in real life.
let clock = document.querySelector('.timer')
let interval = null;
let milliseconds = 0;
let seconds =0;
window.addEventListener('click', () => {
interval = setInterval(startClock,10)
})
document.addEventListener('keyup', event => {
if (event.code === 'Space') {
clearInterval(interval);
setTimeout(()=>{
alert(`${seconds}:${milliseconds}`);
},50)
}
})
function startClock(){
milliseconds += 10;
if(milliseconds==1000){
milliseconds = 0;
seconds++;
}
let sec = seconds.toString();
let ms = milliseconds.toString();
if(seconds<10){
sec = `0${seconds}`;
}
if(milliseconds<100){
ms = `0${milliseconds}`;
}
clock.innerHTML =`${sec}:${ms}`;
}
p{
color: rgb(25, 25, 25);
font-size: 170px;
height: 120px;
font-weight: bold;
}
<p class="timer">00:000</p>
for every 10 milliseconds, it works perfect
Even then it's not reliable. It can drift over time, it can be delayed by anything blocking the UI even for the briefest of moments, etc.
Taking a step back... Do you really need your UI clock to display every individual millisecond? Are you observing the results 1,000 times per second? Motion pictures update a couple dozen times per second and we perceive them as fluid continuous motion. What human needs to see 1,000 distinct numbers per second?
Instead, have your clock update the UI at regular intervals (if every 10ms is working for you then that's reasonable, every 50ms would probably be reasonable too) to show the current time. You don't need to create a stopwatch to measure time, the computer is already measuring time and you can query that measurement whenever you like, as often as you like.
All your "stopwatch" needs to do is know when it started and it can always calculate the elapsed milliseconds since then.
You can perhaps try to mimic the more random look and feel of a quickly-ticking millisecond timer by making the intervals an odd number, like 27ms or 41ms.
For example:
let clock = document.querySelector('.timer')
let interval = null;
let startTime = null;
window.addEventListener('click', () => {
startTime = new Date();
interval = setInterval(clockTick, 42)
})
function clockTick(){
let diff = new Date().getTime() - startTime.getTime();
clock.innerHTML =`${Math.floor(diff / 1000)}:${`${diff % 1000}`.padStart(3, "0")}`;
}
p{
color: rgb(25, 25, 25);
font-size: 170px;
height: 120px;
font-weight: bold;
}
<p class="timer">00:000</p>
Since you can't guarantee how long the code inside the interval will take to run, it's better to use the Date api. Instead of relying on the interval, you could run a loop that constantly calculates the ms between now and the start.
Here's an example of this concept:
// assume this runs when the stopwatch starts
let startTime = new Date().getTime()
// this should stop when the user stops the timer, but I'm using a for loop
// for the example
for(let i = 0; i < 100; i++) {
let now = new Date().getTime()
console.log("ms elapsed: " + (now - startTime))
}
Now it doesn't matter how fast the code is; it should always be accurate.
Javascript is single-threaded, which means it can only run one task at a time, blocking everything else.
That's why the browser stops working if you do while(true) {}. You can't scroll, click, and all animations stop while the loop runs.
Instead, I would suggest to use requestForAnimationFrame, so the timer only updates when the screen does a repaint (60, 120, 144 or whatever Hz your monitor has).
My timer stops when you click a second time.
const timerEl = document.getElementById('timer');
var startTime = 0, animationId = 0;
const toggleTimer = () => {
if (startTime == 0) {
startTime = new Date().getTime();
startTimer();
} else {
stopTimer();
updateTimerElement(new Date().getTime());
startTime = 0;
}
}
const startTimer = () => {
updateTimerElement(new Date().getTime());
animationId = requestAnimationFrame(startTimer);
}
const stopTimer = () => {
cancelAnimationFrame(animationId);
}
const updateTimerElement = (currentTime) => {
let passedTime = currentTime - startTime;
const MINUTE = 1000 * 60;
const SECOND = 1000;
let min = Math.floor(passedTime / MINUTE);
passedTime = passedTime - min * MINUTE;
let sec = Math.floor(passedTime / SECOND);
let ms = passedTime - sec * SECOND;
timerEl.innerText = `${addPadding(min)}:${addPadding(sec)}:${addPadding(ms, 3)}`;
}
const addPadding = (number, pad = 2) => {
return String(number).padStart(pad, '0');
}
document.addEventListener('mouseup', () => { toggleTimer() })
body {
display: flex;
justify-content: center;
align-items: center;
min-height: 100vh;
padding: 0;
}
#timer {
font-size: 40vh;
font-weight: bold;
}
<div id="timer">00:00:000</div>

Why isn't my throttled requestAnimationFrame running 60FPS on my 144hz monitor? [duplicate]

This question already has an answer here:
Canvas is drawing with inconsistent speed (requestAnimationFrame)
(1 answer)
Closed 11 months ago.
I want to make my requestAnimationFrame run 60FPS regardless of monitors refresh rate so the game would run at the same speed on every monitor.
Although it seems to work, when I try using chrome DevTools performance tab I can see the FPS being like -> 48, 72, 48, 72....
Here is my throttled version of rAF
let start;
let elapsed;
function startAnimating(timestamp) {
const fpsInterval = 1000 / 60;
if (start === undefined) {
start = timestamp
}
elapsed = timestamp - start;
if (elapsed >= fpsInterval) {
start = timestamp - (elapsed % fpsInterval);
move();
}
requestAnimationFrame(startAnimating);
}
The TL;DR is, requestAnimationFrame() runs whenever it feels like. You can't really throttle it. If you want to try to do that, you should use setTimeout() or setInternal() instead. They'll be called closer to your throttled rate, usually +/- 4ms.
Or you can do what you're doing, which is throttle when you take action, if you want. You'll see in DevTools whatever requestAnimationFrame() is being called at, but your function would only do the move() at 60FPS, or whatever rate best lines up with it. Though, this can create some clunkiness, since you may end up with much slower effective FPSthan what you want, if the intervals between each call by requestAnimationFrame() don't line up well with your target FPS.
Usually a better approach is instead scale all of your changes, such as movement, by the delta of your time since the last call:
let lastTime = Date.now();
function startAnimating() {
const now = Date.now();
const delta = now - lastTime;
lastTime = now;
move(delta); // delta is the ms since the last call
requestAnimationFrame(delta);
}
function move(delta) {
character.moveBy(speedInPxPerSecond * (delta / 1000));
}
startAnimating();
So, if you want your character to move 100px a second, if you multiply that 100 by delta / 1000, you end up with a character that moves exactly (or very, very nearly exactly) 100px a second, regardless if your FPS is 10, 30, 60, or 1000.
...so the game would run at the same speed on every monitor.
With respect, that's not the best way to do that. (It's not just you, people make this mistake all the time. :-) ) Your game should run at the same speed regardless of whether your rAF callbacks are done at 30Hz, 60Hz, 144Hz, or whatever. The way animation and time-based game logic should be written is to look at the current time as of the callback and figure out what to render at that moment. The rAF callbacks should not be what drives the clock of the game. That should be based on an actual clock (for instance, Date.now() or performance.now()).
For example, here's a simple animation done incorrectly (based on calls to rAF). Aside from the fact that it will run at the wrong speed if your refresh rate is not 60Hz, the browser gets busy for a minute and can't update the screen:
// Make the block go left to right in five seconds
// 5sec = 5,000ms. 5sec at 60Hz is 300 callbacks
// 100% / 300 = 0.333333334% per callback.
const block = document.getElementById("block");
let start = Date.now();
updateBlock();
let timerHandle = 0;
busyBrowser();
function busyBrowser() {
timerHandle = setTimeout(() => {
const stop = Date.now() + 100;
while (Date.now() < stop); // NEVER DO THIS FOR REAL
busyBrowser();
}, 230);
}
function updateBlock() {
let left = parseFloat(block.style.left || "0");
left = Math.min(100, left + 0.333333334);
block.style.left = left + "%";
if (left === 100) {
console.log(`Done after ${(Date.now() - start) / 1000} seconds`);
clearInterval(timerHandle);
} else {
requestAnimationFrame(updateBlock);
}
}
#channel {
position: relative;
height: 1rem;
}
#block {
position: absolute;
left: 0;
top: 0;
height: 1rem;
}
Should take five seconds to go left to right.
<div id="channel">
<div id="block">X</div>
</div>
On my system with a 100Hz refresh rate, that takes four seconds, because it's wrong in two ways:
My refresh rate is 100Hz, not 60Hz, but the code assumes it's 60Hz.
There were times when the browser was busy doing "other things" (my busy loop) and couldn't call rAF.
The only reason it's four seconds is the delays (#2); without them, it's three seconds.
Instead, the code in rAF should look at what the time is, and render based on where things should be at that time:
// Make the block go left to right in five seconds
// 5sec = 5,000ms. 5sec at 60Hz is 300 callbacks
// 100% / 300 = 0.333333334% per callback.
const block = document.getElementById("block");
let start = Date.now();
let stop = start + 5000;
updateBlock();
let timerHandle = 0;
busyBrowser();
function busyBrowser() {
timerHandle = setTimeout(() => {
const stop = Date.now() + 100;
while (Date.now() < stop); // NEVER DO THIS FOR REAL
busyBrowser();
}, 230);
}
function updateBlock() {
const elapsed = Date.now() - start;
let left = Math.min(
100,
elapsed * 0.02 // 100 / 5000 = 0.2% per ms
);
block.style.left = left + "%";
if (left === 100) {
console.log(`Done after ${elapsed / 1000} seconds`);
clearInterval(timerHandle);
} else {
requestAnimationFrame(updateBlock);
}
}
#channel {
position: relative;
height: 1rem;
}
#block {
position: absolute;
left: 0;
top: 0;
height: 1rem;
}
Should take five seconds to go left to right.
<div id="channel">
<div id="block">X</div>
</div>
That finishes in five seconds on my machine, despite my faster refresh rate and the browser being intermittently busy.

How to time requestAnimationFrame() independent of refreshrates

I have a situation where I want to animate the width of a 600px wide div to 0px in 1 second. I could use requestAnimationFrame() for this. But I wouldn't really be a 100% sure if the animation will take 1 second.
It would look something like this:
let width = 600;
let animation;
function animateWidth(){
if(width <= 0){
window.cancelAnimationFrame();
}else{
width -= 10; // (600px/60fps)
}
document.getElementById('id1').setAttribute('width', width);
animation = window.requestAnimationFrame(animateWidth);
}
animation = window.requestAnimationFrame(animateWidth);
The thing is, when a device has a different fps it will affect the duration of the animation (at 30fps it will take 2 seconds and at 60 fps it will take one). I want to make sure this duration of the animation is always one second. If the fps-rate is different I would want to change the new values of the width based on the duration (so animating at 30 fps we would change the width by 20 each step(600px/30fps)).
Is there any way I can achieve this while using requestAnimationFrame? If I could get the average interval between frames or the fps that would work I think.
Am I perhaps worrying about something that isn't really a big issue?
What fps can I expect on different devices (mobile, pc, tablet, etc.)?
documentation: https://developer.mozilla.org/en-US/docs/Web/API/Window/requestAnimationFrame
requestAnimationFrame passes the time since the page loaded to the callback so for example
const startValue = 600;
const endValue = 0;
// return a value between start and end as l goes from 0 to 1
function lerp(start, end, l) {
return start + (end - start) * l;
}
const startTime = performance.now();
const durationInSeconds = 1;
const element = document.getElementById('id1');
function animateWidth(now) {
const timeSinceStartInSeconds = (now - startTime) * 0.001;
// l goes from 0 to 1 over durationInSeconds;
const l = Math.min(timeSinceStartInSeconds / durationInSeconds, 1);
element.setAttribute('width', lerp(startValue, endValue, l));
// if we haven't finished request another animation frame
if (l < 1) {
requestAnimationFrame(animateWidth);
}
}
requestAnimationFrame(animateWidth);
#id1 { background: red; }
<canvas id="id1"></canvas>
If it was me I'd probably try to make it a function
// return a value between start and end as l goes from 0 to 1
function lerp(start, end, l) {
return start + (end - start) * l;
}
function animateAttribute(element, attribute, startValue, endValue, duration) {
const startTime = performance.now();
function animate(now) {
const timeSinceStart = (now - startTime) * 0.001;
// l goes from 0 to 1 over durationInSeconds;
const l = Math.min(timeSinceStart / duration, 1);
element.setAttribute(attribute, lerp(startValue, endValue, l));
// if we haven't finished request another animation frame
if (l < 1) {
requestAnimationFrame(animate);
}
}
requestAnimationFrame(animate);
}
const element = document.getElementById('id1');
const attribute = 'width';
const start = 600;
const end= 0;
const duration = 1;
animateAttribute(element, attribute, start, end, duration);
#id1 { background: red; }
<canvas id="id1"></canvas>
Also by passing l to any of these functions and passing the result to lerp you can change how the animation happens to match any of these styles of motion.
As for your other questions
Is there any way I can achieve this while using requestAnimationFrame? If I could get the average interval between frames or the fps that would work I think.
You can compute the interval between frames. Example:
let then = performance.now();
function animate(now) {
deltaTimeInMilliseconds = (now - then);
then = now;
...
requestAnimationFrame(animate);
}
requestAnimationFrame(animate);
Am I perhaps worrying about something that isn't really a big issue?
Only you can answer that question
What fps can I expect on different devices (mobile, pc, tablet, etc.)?
Most devices are 60fps but there are gamer monitors that run at 120fps or 240fps as well as VR (and WebVR) which generally runs at 90fps or more and you can use browsers inside VR. Whether or not you care about any of those situations is up to you.
Measuring time since the animation start and using it as a reference in width calculation would be a common practice here.
Using this code the animation will last one second no matter what FPS the device has.
const el = document.getElementById('id1');
const start = Date.now();
function animateWidth() {
const t = (Date.now() - start) / 1000; // 1000 - one second
if(t >= 1) {
el.setAttribute('width', 0);
}
else {
el.setAttribute('width', 600 * (1 - t));
window.requestAnimationFrame(animateWidth);
}
}
animateWidth();

Convert jQuery recursive animate to requestAnimationFrame

I need time precision during an animation divided into steps.
The progress bar’s width is increased every 100ms by 20 pixels. I use jQuery’s animate() to animate the width.
Logging Date.now(), it’s clear that the time changes and it is not precise.
http://jsfiddle.net/trustweb/az3aE/23/
function animateProgress() {
console.log(Date.now() - progressTime);
progressTime = Date.now();
progress_width = $(progress).width();
if (progress_width < progressLimit) {
$(progress).animate(
{ width: '+=20' }, '' + progressTime, "linear", animateProgress
);
}
}
I’ve been reading about requestAnimationFrame, and I guess it’s the right way; how can I convert the function above to use requestAnimationFrame, or achieve precise timing in some other way?
You don’t need requestAnimationFrame. Use a transition instead and setInterval:
var progressBar = document.getElementById("progress");
var start = new Date();
var timer = setInterval(function() {
var t = new Date() - start;
if (t < 500) {
progressBar.style.width = (t * 20 / 100 | 0) + "px";
} else {
progressBar.style.width = "100px";
clearInterval(timer);
}
}, 100);
Demo (if I understand you correctly – your jsFiddle doesn’t have any elements involved, so it’s hard to tell)

Controlling fps with requestAnimationFrame?

It seems like requestAnimationFrame is the de facto way to animate things now. It worked pretty well for me for the most part, but right now I'm trying to do some canvas animations and I was wondering: Is there any way to make sure it runs at a certain fps? I understand that the purpose of rAF is for consistently smooth animations, and I might run the risk of making my animation choppy, but right now it seems to run at drastically different speeds pretty arbitrarily, and I'm wondering if there's a way to combat that somehow.
I'd use setInterval but I want the optimizations that rAF offers (especially automatically stopping when the tab is in focus).
In case someone wants to look at my code, it's pretty much:
animateFlash: function() {
ctx_fg.clearRect(0,0,canvasWidth,canvasHeight);
ctx_fg.fillStyle = 'rgba(177,39,116,1)';
ctx_fg.strokeStyle = 'none';
ctx_fg.beginPath();
for(var i in nodes) {
nodes[i].drawFlash();
}
ctx_fg.fill();
ctx_fg.closePath();
var instance = this;
var rafID = requestAnimationFrame(function(){
instance.animateFlash();
})
var unfinishedNodes = nodes.filter(function(elem){
return elem.timer < timerMax;
});
if(unfinishedNodes.length === 0) {
console.log("done");
cancelAnimationFrame(rafID);
instance.animate();
}
}
Where Node.drawFlash() is just some code that determines radius based off a counter variable and then draws a circle.
How to throttle requestAnimationFrame to a specific frame rate
Demo throttling at 5 FPS: http://jsfiddle.net/m1erickson/CtsY3/
This method works by testing the elapsed time since executing the last frame loop.
Your drawing code executes only when your specified FPS interval has elapsed.
The first part of the code sets some variables used to calculate elapsed time.
var stop = false;
var frameCount = 0;
var $results = $("#results");
var fps, fpsInterval, startTime, now, then, elapsed;
// initialize the timer variables and start the animation
function startAnimating(fps) {
fpsInterval = 1000 / fps;
then = Date.now();
startTime = then;
animate();
}
And this code is the actual requestAnimationFrame loop which draws at your specified FPS.
// the animation loop calculates time elapsed since the last loop
// and only draws if your specified fps interval is achieved
function animate() {
// request another frame
requestAnimationFrame(animate);
// calc elapsed time since last loop
now = Date.now();
elapsed = now - then;
// if enough time has elapsed, draw the next frame
if (elapsed > fpsInterval) {
// Get ready for next frame by setting then=now, but also adjust for your
// specified fpsInterval not being a multiple of RAF's interval (16.7ms)
then = now - (elapsed % fpsInterval);
// Put your drawing code here
}
}
I suggest wrapping your call to requestAnimationFrame in a setTimeout:
const fps = 25;
function animate() {
// perform some animation task here
setTimeout(() => {
requestAnimationFrame(animate);
}, 1000 / fps);
}
animate();
You need to call requestAnimationFrame from within setTimeout, rather than the other way around, because requestAnimationFrame schedules your function to run right before the next repaint, and if you delay your update further using setTimeout you will have missed that time window. However, doing the reverse is sound, since you’re simply waiting a period of time before making the request.
Update 2016/6
The problem throttling the frame rate is that the screen has a constant update rate, typically 60 FPS.
If we want 24 FPS we will never get the true 24 fps on the screen, we can time it as such but not show it as the monitor can only show synced frames at 15 fps, 30 fps or 60 fps (some monitors also 120 fps).
However, for timing purposes we can calculate and update when possible.
You can build all the logic for controlling the frame-rate by encapsulating calculations and callbacks into an object:
function FpsCtrl(fps, callback) {
var delay = 1000 / fps, // calc. time per frame
time = null, // start time
frame = -1, // frame count
tref; // rAF time reference
function loop(timestamp) {
if (time === null) time = timestamp; // init start time
var seg = Math.floor((timestamp - time) / delay); // calc frame no.
if (seg > frame) { // moved to next frame?
frame = seg; // update
callback({ // callback function
time: timestamp,
frame: frame
})
}
tref = requestAnimationFrame(loop)
}
}
Then add some controller and configuration code:
// play status
this.isPlaying = false;
// set frame-rate
this.frameRate = function(newfps) {
if (!arguments.length) return fps;
fps = newfps;
delay = 1000 / fps;
frame = -1;
time = null;
};
// enable starting/pausing of the object
this.start = function() {
if (!this.isPlaying) {
this.isPlaying = true;
tref = requestAnimationFrame(loop);
}
};
this.pause = function() {
if (this.isPlaying) {
cancelAnimationFrame(tref);
this.isPlaying = false;
time = null;
frame = -1;
}
};
Usage
It becomes very simple - now, all that we have to do is to create an instance by setting callback function and desired frame rate just like this:
var fc = new FpsCtrl(24, function(e) {
// render each frame here
});
Then start (which could be the default behavior if desired):
fc.start();
That's it, all the logic is handled internally.
Demo
var ctx = c.getContext("2d"), pTime = 0, mTime = 0, x = 0;
ctx.font = "20px sans-serif";
// update canvas with some information and animation
var fps = new FpsCtrl(12, function(e) {
ctx.clearRect(0, 0, c.width, c.height);
ctx.fillText("FPS: " + fps.frameRate() +
" Frame: " + e.frame +
" Time: " + (e.time - pTime).toFixed(1), 4, 30);
pTime = e.time;
var x = (pTime - mTime) * 0.1;
if (x > c.width) mTime = pTime;
ctx.fillRect(x, 50, 10, 10)
})
// start the loop
fps.start();
// UI
bState.onclick = function() {
fps.isPlaying ? fps.pause() : fps.start();
};
sFPS.onchange = function() {
fps.frameRate(+this.value)
};
function FpsCtrl(fps, callback) {
var delay = 1000 / fps,
time = null,
frame = -1,
tref;
function loop(timestamp) {
if (time === null) time = timestamp;
var seg = Math.floor((timestamp - time) / delay);
if (seg > frame) {
frame = seg;
callback({
time: timestamp,
frame: frame
})
}
tref = requestAnimationFrame(loop)
}
this.isPlaying = false;
this.frameRate = function(newfps) {
if (!arguments.length) return fps;
fps = newfps;
delay = 1000 / fps;
frame = -1;
time = null;
};
this.start = function() {
if (!this.isPlaying) {
this.isPlaying = true;
tref = requestAnimationFrame(loop);
}
};
this.pause = function() {
if (this.isPlaying) {
cancelAnimationFrame(tref);
this.isPlaying = false;
time = null;
frame = -1;
}
};
}
body {font:16px sans-serif}
<label>Framerate: <select id=sFPS>
<option>12</option>
<option>15</option>
<option>24</option>
<option>25</option>
<option>29.97</option>
<option>30</option>
<option>60</option>
</select></label><br>
<canvas id=c height=60></canvas><br>
<button id=bState>Start/Stop</button>
Old answer
The main purpose of requestAnimationFrame is to sync updates to the monitor's refresh rate. This will require you to animate at the FPS of the monitor or a factor of it (ie. 60, 30, 15 FPS for a typical refresh rate # 60 Hz).
If you want a more arbitrary FPS then there is no point using rAF as the frame rate will never match the monitor's update frequency anyways (just a frame here and there) which simply cannot give you a smooth animation (as with all frame re-timings) and you can might as well use setTimeout or setInterval instead.
This is also a well known problem in the professional video industry when you want to playback a video at a different FPS then the device showing it refresh at. Many techniques has been used such as frame blending and complex re-timing re-building intermediate frames based on motion vectors, but with canvas these techniques are not available and the result will always be jerky video.
var FPS = 24; /// "silver screen"
var isPlaying = true;
function loop() {
if (isPlaying) setTimeout(loop, 1000 / FPS);
... code for frame here
}
The reason why we place setTimeout first (and why some place rAF first when a poly-fill is used) is that this will be more accurate as the setTimeout will queue an event immediately when the loop starts so that no matter how much time the remaining code will use (provided it doesn't exceed the timeout interval) the next call will be at the interval it represents (for pure rAF this is not essential as rAF will try to jump onto the next frame in any case).
Also worth to note that placing it first will also risk calls stacking up as with setInterval. setInterval may be slightly more accurate for this use.
And you can use setInterval instead outside the loop to do the same.
var FPS = 29.97; /// NTSC
var rememberMe = setInterval(loop, 1000 / FPS);
function loop() {
... code for frame here
}
And to stop the loop:
clearInterval(rememberMe);
In order to reduce frame rate when the tab gets blurred you can add a factor like this:
var isFocus = 1;
var FPS = 25;
function loop() {
setTimeout(loop, 1000 / (isFocus * FPS)); /// note the change here
... code for frame here
}
window.onblur = function() {
isFocus = 0.5; /// reduce FPS to half
}
window.onfocus = function() {
isFocus = 1; /// full FPS
}
This way you can reduce the FPS to 1/4 etc.
These are all good ideas in theory, until you go deep. The problem is you can't throttle an RAF without de-synchronizing it, defeating it's very purpose for existing. So you let it run at full-speed, and update your data in a separate loop, or even a separate thread!
Yes, I said it. You can do multi-threaded JavaScript in the browser!
There are two methods I know that work extremely well without jank, using far less juice and creating less heat. Accurate human-scale timing and machine efficiency are the net result.
Apologies if this is a little wordy, but here goes...
Method 1: Update data via setInterval, and graphics via RAF.
Use a separate setInterval for updating translation and rotation values, physics, collisions, etc. Keep those values in an object for each animated element. Assign the transform string to a variable in the object each setInterval 'frame'. Keep these objects in an array. Set your interval to your desired fps in ms: ms=(1000/fps). This keeps a steady clock that allows the same fps on any device, regardless of RAF speed. Do not assign the transforms to the elements here!
In a requestAnimationFrame loop, iterate through your array with an old-school for loop-- do not use the newer forms here, they are slow!
for(var i=0; i<sprite.length-1; i++){ rafUpdate(sprite[i]); }
In your rafUpdate function, get the transform string from your js object in the array, and its elements id. You should already have your 'sprite' elements attached to a variable or easily accessible through other means so you don't lose time 'get'-ing them in the RAF. Keeping them in an object named after their html id's works pretty good. Set that part up before it even goes into your SI or RAF.
Use the RAF to update your transforms only, use only 3D transforms (even for 2d), and set css "will-change: transform;" on elements that will change. This keeps your transforms synced to the native refresh rate as much as possible, kicks in the GPU, and tells the browser where to concentrate most.
So you should have something like this pseudocode...
// refs to elements to be transformed, kept in an array
var element = [
mario: document.getElementById('mario'),
luigi: document.getElementById('luigi')
//...etc.
]
var sprite = [ // read/write this with SI. read-only from RAF
mario: { id: mario ....physics data, id, and updated transform string (from SI) here },
luigi: { id: luigi .....same }
//...and so forth
] // also kept in an array (for efficient iteration)
//update one sprite js object
//data manipulation, CPU tasks for each sprite object
//(physics, collisions, and transform-string updates here.)
//pass the object (by reference).
var SIupdate = function(object){
// get pos/rot and update with movement
object.pos.x += object.mov.pos.x; // example, motion along x axis
// and so on for y and z movement
// and xyz rotational motion, scripted scaling etc
// build transform string ie
object.transform =
'translate3d('+
object.pos.x+','+
object.pos.y+','+
object.pos.z+
') '+
// assign rotations, order depends on purpose and set-up.
'rotationZ('+object.rot.z+') '+
'rotationY('+object.rot.y+') '+
'rotationX('+object.rot.x+') '+
'scale3d('.... if desired
; //...etc. include
}
var fps = 30; //desired controlled frame-rate
// CPU TASKS - SI psuedo-frame data manipulation
setInterval(function(){
// update each objects data
for(var i=0; i<sprite.length-1; i++){ SIupdate(sprite[i]); }
},1000/fps); // note ms = 1000/fps
// GPU TASKS - RAF callback, real frame graphics updates only
var rAf = function(){
// update each objects graphics
for(var i=0; i<sprite.length-1; i++){ rAF.update(sprite[i]) }
window.requestAnimationFrame(rAF); // loop
}
// assign new transform to sprite's element, only if it's transform has changed.
rAF.update = function(object){
if(object.old_transform !== object.transform){
element[object.id].style.transform = transform;
object.old_transform = object.transform;
}
}
window.requestAnimationFrame(rAF); // begin RAF
This keeps your updates to the data objects and transform strings synced to desired 'frame' rate in the SI, and the actual transform assignments in the RAF synced to GPU refresh rate. So the actual graphics updates are only in the RAF, but the changes to the data, and building the transform string are in the SI, thus no jankies but 'time' flows at desired frame-rate.
Flow:
[setup js sprite objects and html element object references]
[setup RAF and SI single-object update functions]
[start SI at percieved/ideal frame-rate]
[iterate through js objects, update data transform string for each]
[loop back to SI]
[start RAF loop]
[iterate through js objects, read object's transform string and assign it to it's html element]
[loop back to RAF]
Method 2. Put the SI in a web-worker. This one is FAAAST and smooth!
Same as method 1, but put the SI in web-worker. It'll run on a totally separate thread then, leaving the page to deal only with the RAF and UI. Pass the sprite array back and forth as a 'transferable object'. This is buko fast. It does not take time to clone or serialize, but it's not like passing by reference in that the reference from the other side is destroyed, so you will need to have both sides pass to the other side, and only update them when present, sort of like passing a note back and forth with your girlfriend in high-school.
Only one can read and write at a time. This is fine so long as they check if it's not undefined to avoid an error. The RAF is FAST and will kick it back immediately, then go through a bunch of GPU frames just checking if it's been sent back yet. The SI in the web-worker will have the sprite array most of the time, and will update positional, movement and physics data, as well as creating the new transform string, then pass it back to the RAF in the page.
This is the fastest way I know to animate elements via script. The two functions will be running as two separate programs, on two separate threads, taking advantage of multi-core CPU's in a way that a single js script does not. Multi-threaded javascript animation.
And it will do so smoothly without jank, but at the actual specified frame-rate, with very little divergence.
Result:
Either of these two methods will ensure your script will run at the same speed on any PC, phone, tablet, etc (within the capabilities of the device and the browser, of course).
How to easily throttle to a specific FPS:
// timestamps are ms passed since document creation.
// lastTimestamp can be initialized to 0, if main loop is executed immediately
var lastTimestamp = 0,
maxFPS = 30,
timestep = 1000 / maxFPS; // ms for each frame
function main(timestamp) {
window.requestAnimationFrame(main);
// skip if timestep ms hasn't passed since last frame
if (timestamp - lastTimestamp < timestep) return;
lastTimestamp = timestamp;
// draw frame here
}
window.requestAnimationFrame(main);
Source: A Detailed Explanation of JavaScript Game Loops and Timing by Isaac Sukin
The simplest way
note: It might behave differently on different screens with different frame rate.
const FPS = 30;
let lastTimestamp = 0;
function update(timestamp) {
requestAnimationFrame(update);
if (timestamp - lastTimestamp < 1000 / FPS) return;
/* <<< PUT YOUR CODE HERE >>> */
lastTimestamp = timestamp;
}
update();
var time = 0;
var time_framerate = 1000; //in milliseconds
function animate(timestamp) {
if(timestamp > time + time_framerate) {
time = timestamp;
//your code
}
window.requestAnimationFrame(animate);
}
A simple solution to this problem is to return from the render loop if the frame is not required to render:
const FPS = 60;
let prevTick = 0;
function render()
{
requestAnimationFrame(render);
// clamp to fixed framerate
let now = Math.round(FPS * Date.now() / 1000);
if (now == prevTick) return;
prevTick = now;
// otherwise, do your stuff ...
}
It's important to know that requestAnimationFrame depends on the users monitor refresh rate (vsync). So, relying on requestAnimationFrame for game speed for example will make it unplayable on 200Hz monitors if you're not using a separate timer mechanism in your simulation.
Skipping requestAnimationFrame cause not smooth(desired) animation at custom fps.
// Input/output DOM elements
var $results = $("#results");
var $fps = $("#fps");
var $period = $("#period");
// Array of FPS samples for graphing
// Animation state/parameters
var fpsInterval, lastDrawTime, frameCount_timed, frameCount, lastSampleTime,
currentFps=0, currentFps_timed=0;
var intervalID, requestID;
// Setup canvas being animated
var canvas = document.getElementById("c");
var canvas_timed = document.getElementById("c2");
canvas_timed.width = canvas.width = 300;
canvas_timed.height = canvas.height = 300;
var ctx = canvas.getContext("2d");
var ctx2 = canvas_timed.getContext("2d");
// Setup input event handlers
$fps.on('click change keyup', function() {
if (this.value > 0) {
fpsInterval = 1000 / +this.value;
}
});
$period.on('click change keyup', function() {
if (this.value > 0) {
if (intervalID) {
clearInterval(intervalID);
}
intervalID = setInterval(sampleFps, +this.value);
}
});
function startAnimating(fps, sampleFreq) {
ctx.fillStyle = ctx2.fillStyle = "#000";
ctx.fillRect(0, 0, canvas.width, canvas.height);
ctx2.fillRect(0, 0, canvas.width, canvas.height);
ctx2.font = ctx.font = "32px sans";
fpsInterval = 1000 / fps;
lastDrawTime = performance.now();
lastSampleTime = lastDrawTime;
frameCount = 0;
frameCount_timed = 0;
animate();
intervalID = setInterval(sampleFps, sampleFreq);
animate_timed()
}
function sampleFps() {
// sample FPS
var now = performance.now();
if (frameCount > 0) {
currentFps =
(frameCount / (now - lastSampleTime) * 1000).toFixed(2);
currentFps_timed =
(frameCount_timed / (now - lastSampleTime) * 1000).toFixed(2);
$results.text(currentFps + " | " + currentFps_timed);
frameCount = 0;
frameCount_timed = 0;
}
lastSampleTime = now;
}
function drawNextFrame(now, canvas, ctx, fpsCount) {
// Just draw an oscillating seconds-hand
var length = Math.min(canvas.width, canvas.height) / 2.1;
var step = 15000;
var theta = (now % step) / step * 2 * Math.PI;
var xCenter = canvas.width / 2;
var yCenter = canvas.height / 2;
var x = xCenter + length * Math.cos(theta);
var y = yCenter + length * Math.sin(theta);
ctx.beginPath();
ctx.moveTo(xCenter, yCenter);
ctx.lineTo(x, y);
ctx.fillStyle = ctx.strokeStyle = 'white';
ctx.stroke();
var theta2 = theta + 3.14/6;
ctx.beginPath();
ctx.moveTo(xCenter, yCenter);
ctx.lineTo(x, y);
ctx.arc(xCenter, yCenter, length*2, theta, theta2);
ctx.fillStyle = "rgba(0,0,0,.1)"
ctx.fill();
ctx.fillStyle = "#000";
ctx.fillRect(0,0,100,30);
ctx.fillStyle = "#080";
ctx.fillText(fpsCount,10,30);
}
// redraw second canvas each fpsInterval (1000/fps)
function animate_timed() {
frameCount_timed++;
drawNextFrame( performance.now(), canvas_timed, ctx2, currentFps_timed);
setTimeout(animate_timed, fpsInterval);
}
function animate(now) {
// request another frame
requestAnimationFrame(animate);
// calc elapsed time since last loop
var elapsed = now - lastDrawTime;
// if enough time has elapsed, draw the next frame
if (elapsed > fpsInterval) {
// Get ready for next frame by setting lastDrawTime=now, but...
// Also, adjust for fpsInterval not being multiple of 16.67
lastDrawTime = now - (elapsed % fpsInterval);
frameCount++;
drawNextFrame(now, canvas, ctx, currentFps);
}
}
startAnimating(+$fps.val(), +$period.val());
input{
width:100px;
}
#tvs{
color:red;
padding:0px 25px;
}
H3{
font-weight:400;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<h3>requestAnimationFrame skipping <span id="tvs">vs.</span> setTimeout() redraw</h3>
<div>
<input id="fps" type="number" value="33"/> FPS:
<span id="results"></span>
</div>
<div>
<input id="period" type="number" value="1000"/> Sample period (fps, ms)
</div>
<canvas id="c"></canvas><canvas id="c2"></canvas>
Original code by #tavnab.
For throttling FPS to any value, pls see jdmayfields answer.
However, for a very quick and easy solution to halve your frame rate, you can simply do your computations only every 2nd frame by:
requestAnimationFrame(render);
function render() {
// ... computations ...
requestAnimationFrame(skipFrame);
}
function skipFrame() { requestAnimationFrame(render); }
Similarly you could always call render but use a variable to control whether you do computations this time or not, allowing you to also cut FPS to a third or fourth (in my case, for a schematic webgl-animation 20fps is still enough while considerably lowering computational load on the clients)
I always do it this very simple way without messing with timestamps:
let fps, eachNthFrame, frameCount;
fps = 30;
//This variable specifies how many frames should be skipped.
//If it is 1 then no frames are skipped. If it is 2, one frame
//is skipped so "eachSecondFrame" is renderd.
eachNthFrame = Math.round((1000 / fps) / 16.66);
//This variable is the number of the current frame. It is set to eachNthFrame so that the
//first frame will be renderd.
frameCount = eachNthFrame;
requestAnimationFrame(frame);
//I think the rest is self-explanatory
function frame() {
if (frameCount === eachNthFrame) {
frameCount = 0;
animate();
}
frameCount++;
requestAnimationFrame(frame);
}
Here is an idea to reach desired fps:
detect browser's animationFrameRate (typically 60fps)
build a bitSet, according to animationFrameRate and your disiredFrameRate (say 24fps)
lookup bitSet and conditionally "continue" the animation frame loop
It uses requestAnimationFrame so the actual frame rate won't be greater than animationFrameRate. you may adjust disiredFrameRate according to animationFrameRate.
I wrote a mini lib, and a canvas animation demo.
function filterNums(nums, jitter = 0.2, downJitter = 1 - 1 / (1 + jitter)) {
let len = nums.length;
let mid = Math.floor(len % 2 === 0 ? len / 2 : (len - 1) / 2), low = mid, high = mid;
let lower = true, higher = true;
let sum = nums[mid], count = 1;
for (let i = 1, j, num; i <= mid; i += 1) {
if (higher) {
j = mid + i;
if (j === len)
break;
num = nums[j];
if (num < (sum / count) * (1 + jitter)) {
sum += num;
count += 1;
high = j;
} else {
higher = false;
}
}
if (lower) {
j = mid - i;
num = nums[j];
if (num > (sum / count) * (1 - downJitter)) {
sum += num;
count += 1;
low = j;
} else {
lower = false;
}
}
}
return nums.slice(low, high + 1);
}
function snapToOrRound(n, values, distance = 3) {
for (let i = 0, v; i < values.length; i += 1) {
v = values[i];
if (n >= v - distance && n <= v + distance) {
return v;
}
}
return Math.round(n);
}
function detectAnimationFrameRate(numIntervals = 6) {
if (typeof numIntervals !== 'number' || !isFinite(numIntervals) || numIntervals < 2) {
throw new RangeError('Argument numIntervals should be a number not less than 2');
}
return new Promise((resolve) => {
let num = Math.floor(numIntervals);
let numFrames = num + 1;
let last;
let intervals = [];
let i = 0;
let tick = () => {
let now = performance.now();
i += 1;
if (i < numFrames) {
requestAnimationFrame(tick);
}
if (i === 1) {
last = now;
} else {
intervals.push(now - last);
last = now;
if (i === numFrames) {
let compareFn = (a, b) => a < b ? -1 : a > b ? 1 : 0;
let sortedIntervals = intervals.slice().sort(compareFn);
let selectedIntervals = filterNums(sortedIntervals, 0.2, 0.1);
let selectedDuration = selectedIntervals.reduce((s, n) => s + n, 0);
let seletedFrameRate = 1000 / (selectedDuration / selectedIntervals.length);
let finalFrameRate = snapToOrRound(seletedFrameRate, [60, 120, 90, 30], 5);
resolve(finalFrameRate);
}
}
};
requestAnimationFrame(() => {
requestAnimationFrame(tick);
});
});
}
function buildFrameBitSet(animationFrameRate, desiredFrameRate){
let bitSet = new Uint8Array(animationFrameRate);
let ratio = desiredFrameRate / animationFrameRate;
if(ratio >= 1)
return bitSet.fill(1);
for(let i = 0, prev = -1, curr; i < animationFrameRate; i += 1, prev = curr){
curr = Math.floor(i * ratio);
bitSet[i] = (curr !== prev) ? 1 : 0;
}
return bitSet;
}
let $ = (s, c = document) => c.querySelector(s);
let $$ = (s, c = document) => Array.prototype.slice.call(c.querySelectorAll(s));
async function main(){
let canvas = $('#digitalClock');
let context2d = canvas.getContext('2d');
await new Promise((resolve) => {
if(window.requestIdleCallback){
requestIdleCallback(resolve, {timeout:3000});
}else{
setTimeout(resolve, 0, {didTimeout: false});
}
});
let animationFrameRate = await detectAnimationFrameRate(10); // 1. detect animation frame rate
let desiredFrameRate = 24;
let frameBits = buildFrameBitSet(animationFrameRate, desiredFrameRate); // 2. build a bit set
let handle;
let i = 0;
let count = 0, then, actualFrameRate = $('#actualFrameRate'); // debug-only
let draw = () => {
if(++i >= animationFrameRate){ // shoud use === if frameBits don't change dynamically
i = 0;
/* debug-only */
let now = performance.now();
let deltaT = now - then;
let fps = 1000 / (deltaT / count);
actualFrameRate.textContent = fps;
then = now;
count = 0;
}
if(frameBits[i] === 0){ // 3. lookup the bit set
handle = requestAnimationFrame(draw);
return;
}
count += 1; // debug-only
let d = new Date();
let text = d.getHours().toString().padStart(2, '0') + ':' +
d.getMinutes().toString().padStart(2, '0') + ':' +
d.getSeconds().toString().padStart(2, '0') + '.' +
(d.getMilliseconds() / 10).toFixed(0).padStart(2, '0');
context2d.fillStyle = '#000000';
context2d.fillRect(0, 0, canvas.width, canvas.height);
context2d.font = '36px monospace';
context2d.fillStyle = '#ffffff';
context2d.fillText(text, 0, 36);
handle = requestAnimationFrame(draw);
};
handle = requestAnimationFrame(() => {
then = performance.now();
handle = requestAnimationFrame(draw);
});
/* debug-only */
$('#animationFrameRate').textContent = animationFrameRate;
let frameRateInput = $('#frameRateInput');
let frameRateOutput = $('#frameRateOutput');
frameRateInput.addEventListener('input', (e) => {
frameRateOutput.value = e.target.value;
});
frameRateInput.max = animationFrameRate;
frameRateOutput.value = frameRateOutput.value = desiredFrameRate;
frameRateInput.addEventListener('change', (e) => {
desiredFrameRate = +e.target.value;
frameBits = buildFrameBitSet(animationFrameRate, desiredFrameRate);
});
}
document.addEventListener('DOMContentLoaded', main);
<div>
Animation Frame Rate: <span id="animationFrameRate">--</span>
</div>
<div>
Desired Frame Rate: <input id="frameRateInput" type="range" min="1" max="60" step="1" list="frameRates" />
<output id="frameRateOutput"></output>
<datalist id="frameRates">
<option>15</option>
<option>24</option>
<option>30</option>
<option>48</option>
<option>60</option>
</datalist>
</div>
<div>
Actual Frame Rate: <span id="actualFrameRate">--</span>
</div>
<canvas id="digitalClock" width="240" height="48"></canvas>
Simplified explanation of earlier answer. At least if you want real-time, accurate throttling without the janks, or dropping frames like bombs. GPU and CPU friendly.
setInterval and setTimeout are both CPU-oriented, not GPU.
requestAnimationFrame is purely GPU-oriented.
Run them separately. It's simple and not janky. In your setInterval, update your math and create a little CSS script in a string. With your RAF loop, only use that script to update the new coordinates of your elements. Don't do anything else in the RAF loop.
The RAF is tied inherently to the GPU. Whenever the script does not change (i.e. because the SI is running a gazillion times slower), Chromium-based browsers know they do not need to do anything, because there are no changes. So the on-the-fly script created each "frame", say 60 times per second, is still the same for say 1000 RAF GPU frames, but it knows nothing has changed, and the net result is it wastes no energy on this. If you check in DevTools, you will see your GPU frame-rate registers at the rate delineated by the setInterval.
Truely, it is just that simple. Separate them, and they will cooperate.
No jankies.
I tried multiple solutions provided on this question. Even though the solutions work as expected, they result in not so professional output.
Based on my personal experience, I would highly recommend not to control FPS on the browser side, especially using requestAnimationFrame. Because, when you do that, it'll make the frame rendering experience very choppy, users will clearly see the frames jumping and finally, it won't look real or professional at all.
So, my advice would be to control the FPS from the server side at the time of sending itself and simply render the frames as soon as you receive them on the browser side.
Note: if you still want to control on the client-side, try avoiding
usage of setTimeout or Date object in your logic of controlling fps.
Because, when the FPS is high, these will introduce their own delay in
terms of event loops or object creations.
Here's a good explanation I found: CreativeJS.com, to wrap a setTimeou) call inside the function passed to requestAnimationFrame. My concern with a "plain" requestionAnimationFrame would be, "what if I only want it to animate three times a second?" Even with requestAnimationFrame (as opposed to setTimeout) is that it still wastes (some) amount of "energy" (meaning that the Browser code is doing something, and possibly slowing the system down) 60 or 120 or however many times a second, as opposed to only two or three times a second (as you might want).
Most of the time I run my browsers with JavaScript intentially off for just this reason. But, I'm using Yosemite 10.10.3, and I think there's some kind of timer problem with it - at least on my old system (relatively old - meaning 2011).

Categories

Resources