Notice: The WebPlatform project has been discontinued when the Stewards partnership agreement ended in September 2015. This site has been frozen, and the assets we have created will remain.

requestAnimationFrame

Summary

A method to invoke at the optimal time a callback to update the frame of an animation.

Method of dom/Windowdom/Window

Syntax

var handle = window.requestAnimationFrame(/* see parameter list */);

Parameters

callback

Data-type
function

The animation code to be run when the system is ready.

Return Value

Returns an object of type NumberNumber

A handle or ID to the animationFrame request that can be used to cancel the request if needed.

Examples

<!DOCTYPE html>
<html>
<head>
<title>requestAnimationFrame</title>
<style type="text/css">
div { position: absolute; left: 10px; top:100px; padding: 50px;
  background: crimson; color: white }
</style>

</head>
<body>

<div id="animated">Hello there.</div>
<button onclick="start()">Start</button>
<button onclick="stop()">Stop</button>
    <script type="text/javascript">
        var elm = document.getElementById("animated");
        var stopped;
        var requestId = 0;
        var starttime;

        function render(time) {
            // set left style to a function of time.
          if (!stopped) {
            elm.style.left = ((Date.now() - starttime) / 4 % 600) + "px";
            requestId = window.requestAnimationFrame(render);
            }
        }

        function start() {
            starttime = Date.now();
            requestId = window.requestAnimationFrame(render);
            stopped = false;
        }
        function stop() {
            if (requestId) {
                window.cancelAnimationFrame(requestId);
            }
            stopped = true;
        }


</script>


</body></html>

Notes

Unlike older animation techniques based on setTimeout and setInterval methods, requestAnimationFrame based animation occurs when the system is ready. This leads to smoother animations and less power consumption than animations because requestAnimationFrame takes the visibility of the web application and the refresh rate of the display into account, The requestAnimationFrame method creates only a single animation request. To create continous animation, a new request must be registered for each frame. To cancel an animation request before the animation function is called back, use cancelAnimationFrame.

Related specifications

Timing control for script-based animations
W3C Working Draft

Attributions