Sunday, May 19, 2024
 Popular · Latest · Hot · Upcoming
138
rated 0 times [  139] [ 1]  / answers: 1 / hits: 16459  / 12 Years ago, mon, april 16, 2012, 12:00:00

I have such a function in my JS script:



function heavyWork(){
for (i=0; i<300; i++){
doSomethingHeavy(i);
}
}


Maybe doSomethingHeavy is ok by itself, but repeating it 300 times causes the browser window to be stuck for a non-negligible time. In Chrome it's not that big of a problem because only one Tab is effected; but for Firefox its a complete disaster.



Is there any way to tell the browser/JS to take it easy and not block everything between calls to doSomethingHeavy?


More From » javascript

 Answers
49

You could nest your calls inside a setTimeout call:



for(...) {
setTimeout(function(i) {
return function() { doSomethingHeavy(i); }
}(i), 0);
}


This queues up calls to doSomethingHeavy for immediate execution, but other JavaScript operations can be wedged in between them.



A better solution is to actually have the browser spawn a new non-blocking process via Web Workers, but that's HTML5-specific.



EDIT:



Using setTimeout(fn, 0) actually takes much longer than zero milliseconds -- Firefox, for example, enforces a minimum 4-millisecond wait time. A better approach might be to use setZeroTimeout, which prefers postMessage for instantaneous, interrupt-able function invocation, but use setTimeout as a fallback for older browsers.


[#86209] Saturday, April 14, 2012, 12 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
masonm

Total Points: 167
Total Questions: 87
Total Answers: 103

Location: Rwanda
Member since Wed, Jun 8, 2022
2 Years ago
masonm questions
;