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

前端 未结 5 1114
你的背包
你的背包 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:24

    I'd break out the code creating the divs into a function, and then schedule execution of that function periodically via setTimeout, like this:

    function createThousands(data) {
        var index;
    
        index = 0;
        doAChunk();
    
        function doAChunk() {
            var counter;
    
            for (counter = 50; counter > 0; --counter) {
                // Are we done?
                if (index >= data.length) {
                    // Yup
                    return;
                }
    
                // ...create a div...
    
                // Move to the next
                ++index;
            }
    
            // Schedule the next pass
            setTimeout(doAChunk, 0); // 0 = defer to the browser but come back ASAP
        }
    }
    

    This uses a single closure, doAChunk to do the work. That closure is eligible for garbage collection once its work is done. (More: Closures are not complicated)

    Live example

提交回复
热议问题