RequestAnimationFrame

by jacobwsmith

HTML

<button onclick="start()">Click me to start!</button>
<button onclick="stop()">Click me to stop!</button>
<div id="animated">Hello there.</div>

CSS

div {
    position: absolute;
    left: 10px;
    padding: 50px;
    background: crimson;
    color: white
}

JavaScript

var requestId = 0;

function animate(time) {
    console.log(time);
    document.getElementById("animated").style.left = (time - animationStartTime) % 2000 / 4 + "px";
    requestId = window.requestAnimationFrame(animate);
}

function start() {
    animationStartTime = window.performance.now();
    requestId = window.requestAnimationFrame(animate);
}

function stop() {
    if (requestId) window.cancelAnimationFrame(requestId);
    requestId = 0;
}