Created
September 28, 2017 07:55
-
-
Save dmitryfry/66e652fdc249d621c53721434e0fe618 to your computer and use it in GitHub Desktop.
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
function scrollToTop(scrollDuration) { | |
var cosParameter = window.scrollY / 2, | |
scrollCount = 0, | |
oldTimestamp = performance.now(); | |
function step (newTimestamp) { | |
scrollCount += Math.PI / (scrollDuration / (newTimestamp - oldTimestamp)); | |
if (scrollCount >= Math.PI) window.scrollTo(0, 0); | |
if (window.scrollY === 0) return; | |
window.scrollTo(0, Math.round(cosParameter + cosParameter * Math.cos(scrollCount))); | |
oldTimestamp = newTimestamp; | |
window.requestAnimationFrame(step); | |
} | |
window.requestAnimationFrame(step); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Explanations:
- pi is the length/end point of the cosinus intervall (see above)
- newTimestamp indicates the current time when callbacks queued by requestAnimationFrame begin to fire.
(for more information see https://developer.mozilla.org/en-US/docs/Web/API/window/requestAnimationFrame)
- newTimestamp - oldTimestamp equals the duration