Why does everything display at once, using setTimeout in Javascript?

后端 未结 2 1896
一生所求
一生所求 2020-12-02 03:19

I\'m trying to make a few things scroll down the screen in javascript, however, upon execution, it just says a little and displays everything at once. So it\'s not clearing

相关标签:
2条回答
  • 2020-12-02 03:28

    Try

    function recurse ( cnt ) {
        for (var i in MenuData) {
            $("#Menu").append('<div style="position:relative; left:' + MenuData[i].x + 'px; top:' + PositionArray[i] + 'px; ">123</div>');
        }
        if (cnt < 1000){
           setTimeout(function () { recurse(cnt + 1); }, 500);
        }
    }
    
    $("#Menu").html('');
    if (PositionArray[count] != null) {
        PositionArray[count]++;
    } else {
        PositionArray[count] = 0;
    }
    recurse(0);
    
    0 讨论(0)
  • 2020-12-02 03:35

    As stated in the comments, you are creating 1000 timeouts for 500 ms at the same time - after 500 ms all of them will be executed. What you want is to increase the timeout for every scheduled function:

    setTimeout(function() {
        // do something
    }, count * 500);
    

    However, creating 1000 timeouts at once is not a that good idea. It would be better to use setInterval or call setTimeout "recursively" until a count of 1000 is reached, so that you only have one active timeout at a time.

    var count = 0;
    function update() {
        // do something
        if (++count < 1000)
            setTimeout(update, 500);
        // else everything is done
    }
    update();
    

    Also, if you intend to create timeouts in a loop, be sure to be familiar with closures and their behavior when accessing counter variables after the loop ran.

    0 讨论(0)
提交回复
热议问题