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

后端 未结 3 1231
借酒劲吻你
借酒劲吻你 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: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(...).

提交回复
热议问题