Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Autoscroll with setInterval/clearInterval

Im relatively new to JS coding, and can't get this little number to work. Can anyone tell me what I'm doing wrong?

My JavaScript is:

    incrementScroll = function() {
        window.scrollBy(0, 3) ;
    }

    startScrollLoop = function() {
        scrollLoopId = setInterval( "incrementScroll", 5) ; 
    }

    stopScrollLoop = function() {
        clearInterval( scrollLoopId ) ;
    }

And my HTML is:

<button onclick="startScrollLoop()">AUTO SCROLL</button>
<button onclick="stopScrollLoop ()">STOP SCROLL</button>

Again, many thanks for help. New to all of this and need to make a project work by morning. Cheers.

like image 778
Johnny Venom Avatar asked Nov 19 '25 22:11

Johnny Venom


1 Answers

The first argument to setInterval() should be a function reference, or non-ideally, a string to be eval()'d, which would be a complete function call with (). So remove the quotes:

// Pass the reference to incrementScroll, 
// not a quoted string containing its name.
scrollLoopId = setInterval(incrementScroll, 5); 

And to clear the scroll, you will need to define scrollLoopId at a higher scope with var.

// Define outside the function so it is available
// in scope of the stopScrollLoop() function when needed...
var scrollLoopId;
var startScrollLoop = function() {
    scrollLoopId = setInterval( incrementScroll, 5) ; 
}

Jsfiddle demo

(uses a slower scroll speed to give you a chance to click the stop button in the middle of the text)

Note that it is good practice to use the var keyword with each of these. even though they would end up at window scope anyway (assuming they're not being defined inside another function).

// Define with var
var incrementScroll = function() {
  window.scrollBy(0, 3);
}
like image 120
Michael Berkowski Avatar answered Nov 22 '25 12:11

Michael Berkowski



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!