I have a long running function. Which iterates through a large array and performs a function within each loop.
longFunction : function(){
var self =
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);
}
})();
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(...)
.
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