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

后端 未结 2 1913
一生所求
一生所求 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: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.

提交回复
热议问题