SOURCE

console 命令行工具 X clear

                    
>
console
var box = document.getElementById('box'), // the box
    boxPos = 10, // the box's position
    limit = 300; // how far the box can go before it switches direction
 
function draw() {
    box.style.left = boxPos + 'px';
}

// Re-adjust the velocity now that it's not dependent on FPS
var boxVelocity = 0.08,
    delta = 0;

function update(delta) { // new delta parameter
    boxPos += boxVelocity * delta; // velocity is now time-sensitive
    // Switch directions if we go too far
    if (boxPos >= limit || boxPos <= 0) boxVelocity = -boxVelocity;
}

var lastFrameTimeMs = 0, // The last time the loop was run
    maxFPS = 60; // The maximum FPS we want to allow

// We want to simulate 1000 ms / 60 FPS = 16.667 ms per frame every time we run update()
var timestep = 1000 / 60;

function mainLoop(timestamp) {
    // Throttle the frame rate.    
    if (timestamp < lastFrameTimeMs + (1000 / maxFPS)) {
        requestAnimationFrame(mainLoop);
        return;
    }
 
    // Track the accumulated time that hasn't been simulated yet
    delta += timestamp - lastFrameTimeMs; // note += here
    lastFrameTimeMs = timestamp;
 
    // Simulate the total elapsed time in fixed-size chunks
    while (delta >= timestep) {
        update(timestep);
        delta -= timestep;
    }
    draw();
    requestAnimationFrame(mainLoop);
}

// Start things off
requestAnimationFrame(mainLoop);
<div id="box"></div>
#box {
    background-color: red;
    height: 50px;
    left: 150px;
    position: absolute;
    top: 10px;
    width: 50px;
}