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)) {
frameID = 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);
frameID = requestAnimationFrame(mainLoop);
}
function panic() {
delta = 0;
}
var frameID;
var running = false,
started = false;
function stop() {
running = false;
started = false;
cancelAnimationFrame(frameID);
}
function start() {
if (!started) {
started = true;
frameID = requestAnimationFrame(function(timestamp) {
draw(1);
running = true;
lastFrameTimeMs = timestamp;
lastFpsUpdate = timestamp;
framesThisSecond = 0;
frameID = requestAnimationFrame(mainLoop);
});
}
}
start()
document.getElementById('start').onclick = start
document.getElementById('stop').onclick = stop
<div id="box"></div>
<div id="fpsDisplay"></div>
<button id="start">start</button>
<button id="stop">stop</button>
#box {
background-color: red;
height: 50px;
left: 150px;
position: absolute;
top: 10px;
width: 50px;
}