doubts with setTimeout

0

I'm good at learning how to program and writing a code I had a very curious problem I try to make the scroll go slow when I click an anchor in the menu but it did not work when I wrote my line (comment below on the code), searching the internet I found an alternative line in which the function runs as a string and concatenates what I do not understand why to do it that way? and why does not it work the way I wrote it?

the code is as follows

for(let i = 0.1 ; i < height; i += 0.1){

            // window.setTimeout(scrollTo(0, "+i")", 0) linea que yo escribi y no funciono
            setTimeout("window.scrollTo(0, "+ i +")", 0.1); //linea alternativa q encontre en internet y si funciono

        } 
    
asked by Carlos Puente 21.06.2018 в 00:58
source

2 answers

2

If you do it with a for loop you are increasing the value of i before the set timeout is executed, because setTimeout runs asynchronously and goes in another call stack with what the entire for loop will be executed before the setTimeout and when this happens i will have the maximum value and will make the scroll of a jump.

What you have to do is a recursive function (that calls itself that contains a setTimeout and that it advances to a scroll and with a condition that determines if it keeps scrolling or does not call the same function with the parameters of scroll and i increased.

function scrollSlow (i, height, topHeight, speed) {
 setTimeout(function () {
     window.scrollTo(0, height);
     if ( i < topHeight ){
         scrollSlow(++i, ++height, topHeight, speed)
     }         
 }, speed);

}
scrollSlow(0, 1, 200, 1);
    
answered by 21.06.2018 / 13:15
source
1

For your line to work, you should write your line in one of these ways:

  • Option 1: pass as a first argument a function that will execute the scrollTo (in this case it is a arrow function ):

    for(let i = 0.1; i < height; i += 0.1) { setTimeout(() => scrollTo(0, i), 0) }

  • Option 2: (the response of the partner), which supports as a string the function to execute

    for(let i = 0.1; i < height; i += 0.1) { setTimeout("scrollTo(0, " + i + ")", 0) }

The window would be optional to write it.

    
answered by 21.06.2018 в 02:18