back to Overview

$.loop()

Runs an animation loop.
Web module only.

Syntax

$.loop(paintCallback)

Parameters

paintCallback
a callback function(timestamp, stopFunc) that will be invoked repeatedly to prepare a frame. Parameters given to callback:
timestamp
The number of miliseconds since the animation's start (possibly as high-precision double, if the browser supports this).
stop
Call this function() to stop the currently running animation.
The callback's return value will be ignored.
(return value)
a function() that stops the currently running animation. This is the same function that is also given to the callback.

Description

Runs an animation loop. The given callback method will be invoked repeatedly to create a new animation frame. In modern browsers, requestAnimationFrame will be used to invoke the callback every time the browser is ready for a new animation frame. The exact frequency is determined by the browser and may vary depending on factors such as the time needed to render the current page, the screen's framerate and whether the page is currently visible to the user. In older browsers the callback function will be invoked approximately every 33 milliseconds.

An animation loop runs indefinitely. To stop it, you have two options:

  • Invoke the stop() function that $.loop() that will return.
  • The animation callback receives the same stop() function as second argument, so the callback can end the animation itself.

Example

Animates a div by moving along in a circle.

  var myDiv = $$('#myAnimatedDiv');
  var rotationsPerMs = 1000;                           // one rotation per second
  var radius = 100;
  var d = 3000;                                        // duration in ms
  $.loop(function(t, stopFunc) {
    var a = 2 * Math.PI * Math.min(t, d) / rotationsPerMs; // angular position
    myDiv.style.left = (radius * Math.cos(a) + ' px';
    myDiv.style.top = (radius * Math.sin(a) + ' px';
    if (t > d)                                         // time is up: call stopFunc()!
      stopFunc();
  });

See also..

  • animate() for simple, property-based animations.

Comments

comments powered by Disqus

back to Overview

Functions