Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Use requestAnimationFrame instead of setInterval, save cpu cycles for animation #9

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
20 changes: 15 additions & 5 deletions scrollability.js
Original file line number Diff line number Diff line change
Expand Up @@ -31,10 +31,16 @@ var kPageEscapeVelocity = 50;
// Vertical margin of scrollbar
var kScrollbarMargin = 2;

_requestAnimationFrame = (function() {
var poormansRAF = function(animate) {
window.setTimeout(animate, 1000 / 60);
}
return window.requestAnimationFrame || window.webkitRequestAnimationFrame || poormansRAF;
})();
// ===============================================================================================

var startX, startY, touchX, touchY, touchDown, touchMoved;
var animationInterval = 0;
var inAnimation = false;
var touchTargets = [];

var scrollers = {
Expand Down Expand Up @@ -72,7 +78,8 @@ function onTouchStart(event) {
}
}

animationInterval = setInterval(touchAnimation, 0);
_requestAnimationFrame(touchAnimation);
inAnimation = true;
}

var d = document;
Expand Down Expand Up @@ -326,6 +333,9 @@ function createTarget(target, startX, startY, startTime) {
}

function touchAnimation() {
if (!inAnimation) {
return
}
var time = new Date().getTime();

// Animate each of the targets
Expand All @@ -343,6 +353,7 @@ function touchAnimation() {
if (!touchTargets.length) {
stopAnimation();
}
_requestAnimationFrame(touchAnimation);
}

// *************************************************************************************************
Expand Down Expand Up @@ -396,9 +407,8 @@ function releaseTouched(touched) {
}

function stopAnimation() {
if (animationInterval) {
clearInterval(animationInterval);
animationInterval = 0;
if (inAnimation) {
inAnimation = false;

for (var i = 0; i < touchTargets.length; ++i) {
var target = touchTargets[i];
Expand Down