HiveBrain v1.2.0
Get Started
← Back to all entries
patternjavascriptMinor

Better ways of making a scroller

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
scrollerwaysbettermaking

Problem

http://jsfiddle.net/xkuZF/6/

function func() {
    document.body.scrollTop++;
}

window.onmouseover = function() {
    clearInterval(interval);
};

window.onmouseout = function() {
    interval = setInterval(func);
};

var interval =  setInterval(func);


Do you think that there are any better ways of doing this code?

Better:

  • More options



  • Less code

Solution

To your questions:

-
More options; sure you could provide a wait time to setInterval to control the speed of the scrolling down, you could also increase the scrollTop increment to make it scroll down faster.

-
Less code; I think this is pretty much the bare minimum, a little too bare really.

I think func and interval are very generic names, I wasnt even sure if the code works / what it does until I clicked the fiddle link.

I would counter propose the following code, it is longer, but far more readable.

var scrollDownInterval;

function scrollDown() {
  document.body.scrollTop++;
}

function startScrollingDown(){
  scrollDownInterval = setInterval( scrollDown );
}

function stopScrollingDown(){
  clearInterval( scrollDownInterval );
}

window.onmouseover = function() {
  stopScrollingDown();
};

window.onmouseout = function() {
  startScrollingDown();
};

//Start scrolling down immediately
startScrollingDown();

Code Snippets

var scrollDownInterval;

function scrollDown() {
  document.body.scrollTop++;
}

function startScrollingDown(){
  scrollDownInterval = setInterval( scrollDown );
}

function stopScrollingDown(){
  clearInterval( scrollDownInterval );
}

window.onmouseover = function() {
  stopScrollingDown();
};

window.onmouseout = function() {
  startScrollingDown();
};

//Start scrolling down immediately
startScrollingDown();

Context

StackExchange Code Review Q#3464, answer score: 2

Revisions (0)

No revisions yet.