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

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

    it takes much time because the reflows. you should create a document fragment and then adding the brats.

    When does reflow happen in a DOM environment?

    Javascript Performance - Dom Reflow - Google Article

    sleeping will not solve your problem

    on the other hand, you creating a string containing the innerhtml and the add to innerhtml. the string stuff really dont needs a big performance, but when you execute the .innerhtml command, it starts a process, which parse your string and creating elements and appending them. you cant interrupt or add a delay.

    the innerhtml process cannot be sleeped or interrupted.

    you need to generate the elements one by one, and after 50 elemnts added, create a settimeout delay.

    var frag = document.createDocumentFragment();
    
    function addelements() {
    
       var e;
       for(i=0;i<50;++i) {
           e = document.createElement('div');
           frag.appendChild(e);
       }
       dest.appendChild(frag);
       window.setTimeout(addelements,1000);
    
    }
    

提交回复
热议问题