Minor performance optimizations

This commit is contained in:
SleepWalker
2016-08-14 12:01:04 +03:00
parent 6fc83505db
commit a91e2e99b3
5 changed files with 30 additions and 24 deletions

View File

@@ -4,34 +4,35 @@
* @see http://ariya.ofilabs.com/2013/11/javascript-kinetic-scrolling-part-2.html
*/
const requestAnimationFrame = window.requestAnimationFrame || window.mozRequestAnimationFrame
|| window.webkitRequestAnimationFrame || window.msRequestAnimationFrame;
import { rAF } from 'functions';
const TIME_CONSTANT = 100; // heigher numbers - slower animation
export default function scrollTo(y, viewPort) {
const start = Date.now();
const {scrollTop} = viewPort;
const amplitude = y - scrollTop;
let scrollWasTouched = false;
rAF(() => { // wrap in rAF to optimize initial reading of scrollTop
const {scrollTop} = viewPort;
const amplitude = y - scrollTop;
requestAnimationFrame(function animateScroll() {
const elapsed = Date.now() - start;
(function animateScroll() {
const elapsed = Date.now() - start;
let delta = -amplitude * Math.exp(-elapsed / TIME_CONSTANT);
let delta = -amplitude * Math.exp(-elapsed / TIME_CONSTANT);
if (Math.abs(delta) > 0.5 && !scrollWasTouched) {
requestAnimationFrame(animateScroll);
} else {
delta = 0;
document.removeEventListener('mousewheel', markScrollTouched);
document.removeEventListener('touchstart', markScrollTouched);
}
if (Math.abs(delta) > 0.5 && !scrollWasTouched) {
rAF(animateScroll);
} else {
delta = 0;
document.removeEventListener('mousewheel', markScrollTouched);
document.removeEventListener('touchstart', markScrollTouched);
}
if (scrollWasTouched) {
return;
}
if (scrollWasTouched) {
return;
}
viewPort.scrollTop = y + delta;
viewPort.scrollTop = y + delta;
}());
});
document.addEventListener('mousewheel', markScrollTouched);