Last active
August 29, 2015 14:20
-
-
Save maikelmclauflin/187a9ebb31e959ba2e7a to your computer and use it in GitHub Desktop.
better requestAnimationFrame management
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var now = Date.now || function () { | |
return new Date().getTime(); | |
}, | |
uniqueId = (function () { | |
var cache = {}; | |
return function (prefix, isInt) { | |
var val; | |
if (!prefix) { | |
prefix = ''; | |
} | |
prefix += ''; | |
val = cache[prefix]; | |
if (!val) { | |
val = cache[prefix] = 0; | |
} | |
cache[prefix]++; | |
if (!isInt) { | |
val = prefix + val; | |
} | |
return val; | |
}; | |
}()), | |
AF = (function () { | |
var currentlyRunning, win = window, | |
x = 0, | |
lastTime = 0, | |
vendors = 'ms moz webkit o'.split(' '), | |
fnList = [], | |
addList = [], | |
removeList = [], | |
run = function () { | |
var i = 0, | |
listLen = fnList.length, | |
removeLater = []; | |
fnList = fnList.concat(addList); | |
addList = []; | |
for (; i < listLen; i++) { | |
fnObj = fnList[i]; | |
if (removeList.indexOf(fnObj.id) === -1) { | |
currentlyRunning = fnObj; | |
fnObj.fn(now()); | |
} | |
} | |
currentlyRunning = void 0; | |
for (i = 0; i < removeList.length; i++) { | |
fnList.splice(fnList.indexOf(removeList[i]), 1); | |
} | |
removeList = []; | |
if (fnList.length) { | |
win.requestAnimationFrame(run); | |
} | |
}; | |
for (; x < getLength(vendors) && !win.requestAnimationFrame; ++x) { | |
win.requestAnimationFrame = win[vendors[x] + 'RequestAnimationFrame']; | |
win.cancelAnimationFrame = win[vendors[x] + 'CancelAnimationFrame'] || win[vendors[x] + 'CancelRequestAnimationFrame']; | |
} | |
if (!win.requestAnimationFrame) { | |
win.requestAnimationFrame = function (callback, element) { | |
var currTime = new Date().getTime(), | |
timeToCall = Math.max(0, 16 - (currTime - lastTime)), | |
id = window.setTimeout(function () { | |
callback(currTime + timeToCall); | |
}, timeToCall); | |
lastTime = currTime + timeToCall; | |
return id; | |
}; | |
} | |
if (!win.cancelAnimationFrame) { | |
win.cancelAnimationFrame = function (id) { | |
clearTimeout(id); | |
}; | |
} | |
return { | |
cancel: function (id) { | |
removeList.push(id); | |
}, | |
remove: function () { | |
removeList.push(currentlyRunning.id); | |
}, | |
request: function (fn) { | |
var id = uuid(); | |
if (typeof fn === 'function') { | |
if (!fnList.length) { | |
win.requestAnimationFrame(run); | |
} | |
addList.push({ | |
fn: fn, | |
id: id | |
}); | |
return id; | |
} | |
} | |
}; | |
}()); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment