Your problem is that you are closing over the same variable scrollto_px
in your setTimeout
. When the setTimeout
function actually runs, the value of scrollto_px
is the same value it had at the end of the loop, so you just immediately scroll to that last value. You need to copy to a new variable that your setTimeout
can close over.
Your second problem is that you are setting a timeouts that all trigger at almost the same time. You need to chain your timeouts so that the first timeout occurs after 1000 seconds, and the next occurs 1000 seconds after that. Note that setTimeout
isn't the same as sleep
in other languages. It doesn't suspend execution.
Your third problem is that you have these lines:
scrollto_px = scrollto_px + px_scroll_extra;
window.scrollTo(0,scrollto_px);
After your while loop which will automatically jump all the way to the end.
Here's one way to fix the problems you are having. I removed your while
loop and added a function that will call itself again after a timeout:
function doScroll() {
if (times_scroll_array[0] >= 1) {
scrollto_px = scrollto_px + scroll_speed;
console.log(scrollto_px);
window.scrollTo(0, scrollto_px);
times_scroll_array[0]--;
setTimeout(doScroll, 100);
} else {
scrollto_px = scrollto_px + px_scroll_extra;
window.scrollTo(0, scrollto_px);
}
}
doScroll();
You can see it running here (I changed the timing because 1 second between steps was really slow - but you can adjust it as needed): http://jsfiddle.net/KqRwx/