How to break up a long running function in javascript, but keep performance

后端 未结 3 1232
借酒劲吻你
借酒劲吻你 2021-01-05 10:56

I have a long running function. Which iterates through a large array and performs a function within each loop.

longFunction : function(){
       var self =          


        
3条回答
  •  独厮守ぢ
    2021-01-05 11:37

    Here's some batching code modified from an earlier answer I had written:

    var n = 0,
        max = data.length;
        batch = 100;
    
    (function nextBatch() {
        for (var i = 0; i < batch && n < max; ++i, ++n) {
            myFunc(n);
        }
        if (n < max) {
            setTimeout(nextBatch, 0);
        }
    })();
    

提交回复
热议问题