To infinity and beyond

Written by Kevin Gimbel on , 🍿 3 min. read

While I was re-designing my Website I decided to finally add some JavaScript to it. I'm learning JavaScript for like 2 months now and - to be honest - I finally understand most of the things I'm doing. Yesterday night's topic was a "Back to Top" Button written in Vanilla JS. Actually the code behind it is kinda simple, however, I wrote an endless function that got to infinity and beyond (that's where the title comes from. I'm so funny.)

Because I still like to google around while writing JavaScript I stumbled upon a function that looked okay to me.

function scrollToTop() {
if (document.body.scrollTop!=0 || document.documentElement.scrollTop!=0){
else clearTimeout(timeOut);

The problem with this one was: It didn't work. So I looked around and found setInterval() which seemed to me a bit like setTimeout and - in my opinion - would mix perfect with scrollBy(x,y). I was right, hurray!

So my function then looked a bit like this (I'm not exactly sure, it was kinda late already).

function scrollToTop() {
if(window.scrollY!=0) {
var scrollBack = setInterval(function() {
} else {

I applied the function to a button, the page scrolled up and I was happy. I tweeted about it just to find out that my Interval wasn't cleared and I could never scroll down again after the function was triggered. Yeah! Awesome.

Well, I thought more about it and read again about setInterval and - most important - the actual object I'm checking. scrollY was the right direction and I decided it must be the Interval that's wrong. I was right and came up with this sweet function!

// notice: backTop is my back to top button!
backTop.addEventListener("click",function() {
// setting an interval
var toTop = setInterval(function() {
// if we're not on top of the page
if(window.scrollY != 0) {
// we scroll back to the top [scrollBy(x,y)]

// in case we're at the top (window.scrollY = 0)
} else {
// clear the interval
},25); // the delay between the steps to go back to top. The smaller the number, the slower it goes
// prevent the click to reload the page
}); // end of the Back to Top function

That's it! My sweet little Back To Top Function. I'm sure there are points that could be improved and I'm sure one could add easing to it (I already got something in mind) but for now I'm happy with it.

(Also check out what else I discovered yesterday. It's a YouTube Easter Egg!)

Hi, I'm Kevin!

I'm a DevOps Engineer with a focus on automation and security. Before shifting into DevOps and cloud computing I worked as Front-End Developer, which is still a hobby and field of interest for me.

Hand-made vector avatar of Kevin Gimbel

I'm very passionated about a variety of games - digital, boardgames, and pen & paper; and also interested in Sci-Fi, Cyberpunk, and dystopian books. You can find out more on the about page.