当前位置: 动力学知识库 > 问答 > 编程问答 >

javascript - 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.

网友答案:

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);
}
分享给朋友:
您可能感兴趣的文章:
随机阅读: