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

后端 未结 3 1215
借酒劲吻你
借酒劲吻你 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);
        }
    })();
    
    0 讨论(0)
  • 2021-01-05 11:41

    Actually 1500 timeouts is nothing, so you can simply do this:

    var i1 = 0
    for (var i = 0; i < 1500; i++) setTimeout(function() { doSomething(i1++) }, 0)
    

    System will queue the timeout events for you and they will be called immediately one after another. And if users click anything during execution, they will not notice any lag. And no "script is running too long" thing.

    From my experiments V8 can create 500,000 timeouts per second.

    UPDATE

    If you need i1 passed in order to your worker function, just pass an object with it, and increment the counter inside of your function.

    function doSomething(obj) {
       obj.count++
       ...put actual code here
    }
    var obj = {count: 0}
    for (var i = 0; i < 1500; i++) setTimeout(function() { doSomething(obj) }, 0)
    

    Under Node.js you can aslo use setImmediate(...).

    0 讨论(0)
  • 2021-01-05 11:47

    Is there anything better?

    If you’re OK with it working only in modern browsers – then you should look into “Web Workers”, that let you execute JS in the background.

    https://developer.mozilla.org/en-US/docs/DOM/Using_web_workers

    0 讨论(0)
提交回复
热议问题