Autoscroll with setInterval/clearInterval

笑着哭i 提交于 2019-12-12 15:00:08

问题


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.


回答1:


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);
}


来源:https://stackoverflow.com/questions/13813257/autoscroll-with-setinterval-clearinterval

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!