Skip to content

Instantly share code, notes, and snippets.

@350d
Created October 29, 2014 13:16
Show Gist options
  • Select an option

  • Save 350d/734033841beaac5c5d92 to your computer and use it in GitHub Desktop.

Select an option

Save 350d/734033841beaac5c5d92 to your computer and use it in GitHub Desktop.

Revisions

  1. 350d created this gist Oct 29, 2014.
    41 changes: 41 additions & 0 deletions jquery.raf.js
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,41 @@
    (function(jQuery){
    'use strict';
    if (!Date.now) Date.now = function() { return new Date().getTime(); };

    var animating,
    vendors = ['moz', 'webkit'],
    W = window;

    for (var i = 0; i < vendors.length && !W.requestAnimationFrame; ++i) {
    var vp = vendors[i];
    W.requestAnimationFrame = W[vp+'RequestAnimationFrame'];
    W.cancelAnimationFrame = (W[vp+'CancelAnimationFrame'] || W[vp+'CancelRequestAnimationFrame']);
    }

    function raf() {
    if (animating) {
    requestAnimationFrame(raf);
    jQuery.fx.tick();
    }
    }

    if (!/iP(ad|hone|od).*OS 6/.test(W.navigator.userAgent) && W.requestAnimationFrame && W.cancelAnimationFrame ) {
    jQuery.fx.timer = function(timer) {
    if (timer() && jQuery.timers.push(timer) && !animating) {
    animating = true;
    raf();
    }
    };
    jQuery.fx.stop = function() {
    animating = false;
    };
    } else {
    var lastTime = 0;
    W.requestAnimationFrame = function(callback) {
    var now = Date.now(),
    nextTime = Math.max(lastTime + 16, now);
    return setTimeout(function() { callback(lastTime = nextTime); }, nextTime - now);
    };
    W.cancelAnimationFrame = clearTimeout;
    }
    }(jQuery));