console
var box = document.getElementById('box'),
boxPos = 10,
limit = 300;
var fpsDisplay = document.getElementById('fpsDisplay');
function draw(interp) {
box.style.left = (boxLastPos + (boxPos - boxLastPos) * interp) + 'px';
fpsDisplay.textContent = Math.round(fps) + ' FPS';
}
var boxVelocity = 0.08,
delta = 0;
var boxLastPos = 10;
function update(delta) {
boxLastPos = boxPos;
boxPos += boxVelocity * delta;
if (boxPos >= limit || boxPos <= 0) boxVelocity = -boxVelocity;
}
var lastFrameTimeMs = 0,
maxFPS = 60;
var timestep = 1000 / 60;
var fps = 60,
framesThisSecond = 0,
lastFpsUpdate = 0;
function mainLoop(timestamp) {
if (timestamp < lastFrameTimeMs + (1000 / maxFPS)) {
requestAnimationFrame(mainLoop);
return;
}
if (timestamp > lastFpsUpdate + 1000) {
fps = 0.25 * framesThisSecond + (1 - 0.25) * fps;
lastFpsUpdate = timestamp;
framesThisSecond = 0;
}
framesThisSecond++;
delta += timestamp - lastFrameTimeMs;
lastFrameTimeMs = timestamp;
var numUpdateSteps = 0;
while (delta >= timestep) {
update(timestep);
delta -= timestep;
if (++numUpdateSteps >= 240) {
panic();
break;
}
}
draw(delta / timestep);
requestAnimationFrame(mainLoop);
}
function panic() {
delta = 0;
}
requestAnimationFrame(mainLoop);
<div id="box"></div>
<div id="fpsDisplay"></div>
#box {
background-color: red;
height: 50px;
left: 150px;
position: absolute;
top: 10px;
width: 50px;
}