requestAnimationFrame快速上手

写一个requestAnimationFrame用法的demo:

var lastTime = 0;

function cb() {
    var nowTime = Date.now();
    var id = requestAnimationFrame(cb);

    if (nowTime - lastTime >= 1000) {
        // 需要每秒处理的逻辑
        console.log('==code here==');
        lastTime = nowTime;
    }
}

cb();

polyfill for browsers without native support

var lastTime = 0;
var vendors = ['webkit', 'moz', 'ms', 'o'];

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

if (!window.requestAnimationFrame) {
    window.requestAnimationFrame = function(callback) {
        var currTime = Date.now();
        var timeToCall = Math.max(0, 16 - (currTime - lastTime));
        var id = window.setTimeout(function() { 
            callback(currTime + timeToCall);
        }, timeToCall);
        lastTime = currTime + timeToCall;
        return id;
    }
}

if (!window.cancelAnimationFrame) {
    window.cancelAnimationFrame = function(id) {
        clearTimeout(id);
    }
}

你可能感兴趣的:(js)