[removed] How to put a simple delay in between execution of javascript code?

前端 未结 5 1115
你的背包
你的背包 2020-12-16 01:45

I have a for loop which iterates more than 10,000 times in a javascript code. The for loop creates and adds < div > tags into a box in the current page DOM.



        
5条回答
  •  春和景丽
    2020-12-16 02:28

    There's a handy trick in these situations: use a setTimeout with 0 milliseconds. This will cause your JavaScript to yield to the browser (so it can perform its rendering, respond to user input and so on), but without forcing it to wait a certain amount of time:

    for (i=0;i';
        if (i % 50 == 0 || i == data.length - 1) {
            (function (html) { // Create closure to preserve value of tmpContainer
                setTimeout(function () {
                    // Add to document using html, rather than tmpContainer
    
                }, 0); // 0 milliseconds
            })(tmpContainer);
    
            tmpContainer = ""; // "flush" the buffer
        }
    }
    

    Note: T.J. Crowder correctly mentions below that the above code will create unnecessary functions in each iteration of the loop (one to set up the closure, and another as an argument to setTimeout). This is unlikely to be an issue, but if you wish, you can check out his alternative which only creates the closure function once.

    A word of warning: even though the above code will provide a more pleasant rendering experience, having 10000 tags on a page is not advisable. Every other DOM manipulation will be slower after this because there are many more elements to traverse through, and a much more expensive reflow calculation for any changes to layout.

提交回复
热议问题