All the setTimeouts inside javascript for loop happen at once

前端 未结 2 1184
攒了一身酷
攒了一身酷 2020-12-22 03:43

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

相关标签:
2条回答
  • 2020-12-22 04:29

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

    0 讨论(0)
  • 2020-12-22 04:38

    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);
    
    0 讨论(0)
提交回复
热议问题