B
B
big_hasan2016-09-05 09:13:23
JavaScript
big_hasan, 2016-09-05 09:13:23

Why doesn't the setTimeout delay work in the loop?

You need to smoothly rewind the page to the top by clicking. There is a delay of 100ms in the loop and the current position decreases by 10 pixels with each iteration. When you try to run the page jumps to the top instantly.

var position=window.pageYOffset;
while(position>0)
    {
    setTimeout(function (){window.scrollTo(0,position)}, 100);
    position=position-10;
    }

However, if we add, for example, alert(position); into the body of the loop, you can see that with each iteration, the page actually shifts and the position value actually decreases by 10 pixels. What could be the problem?
UPD: If you set a long delay time (without alert), the page scrolls not instantly, but after a second or two.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
S
Sergey Gornostaev, 2016-09-05
@big_hasan

And you insert alert into the anonymous function that you pass to the setTimeout call. Everything will become clear right away. It's better to do this:

function smoothScroll() {
    if(window.pageYOffset > 0) {
        window.scrollTo(0, window.pageYOffset - 10);
        setTimeout(smoothScroll, 100);
    }
}

setTimeout(smoothScroll, 100);

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question