This function should scroll down from the top of the page to 215 pixels below, with an increasing delay, so that the first window.scrollTo event happens at 10ms, the next at
The timeouts don't all happen at once, they happen with the timing you expect. However, they all try to scroll to a position represented by the same y
variable, so they all use whatever value y
has when the loop finishes.
The usual fix for this is to introduce a closure:
function scrollDown() {
var yFinal = 216,
delay = 0;
for (var y = 0; y < yFinal; y++) {
delay += 10;
(function(position) {
setTimeout(function() {
window.scrollTo(100, position);
}, delay);
})(y);
}
}
(Note also that your y
variable was global: you should declare it with var
to make it local.)
You have to wrap setTimeout
in an anonymous function to pass y
by value and not by reference:
(function(y) {
setTimeout(function() {
window.scrollTo(100,y);
}, delay);
})(y);