summaryrefslogtreecommitdiffstats
path: root/attractors4/request-animation-frame.js
blob: 1de8cd41b9d3142b5f1aa6453a0d9c4848db25b7 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
// -------------------------- requestAnimationFrame -------------------------- //

// https://gist.github.com/1866474

var lastTime = 0;
var prefixes = 'webkit moz ms o'.split(' ');
// get unprefixed rAF and cAF, if present
var rAF = window.requestAnimationFrame;
var cAF = window.cancelAnimationFrame;
// loop through vendor prefixes and get prefixed rAF and cAF
var prefix;
for( var i = 0; i < prefixes.length; i++ ) {
  if ( rAF && cAF ) {
    break;
  }
  prefix = prefixes[i];
  rAF = rAF || window[ prefix + 'RequestAnimationFrame' ];
  cAF  = cAF || window[ prefix + 'CancelAnimationFrame' ] ||
    window[ prefix + 'CancelRequestAnimationFrame' ];
}

// fallback to setTimeout and clearTimeout if either request/cancel is not supported
if ( !rAF || !cAF )  {
  rAF = function( callback ) {
    var currTime = new Date().getTime();
    var timeToCall = Math.max( 0, 16 - ( currTime - lastTime ) );
    var id = window.setTimeout( function() {
      callback( currTime + timeToCall );
    }, timeToCall );
    lastTime = currTime + timeToCall;
    return id;
  };

  cAF = function( id ) {
    window.clearTimeout( id );
  };
}