Tuesday, May 7, 2024
 Popular · Latest · Hot · Upcoming
104
rated 0 times [  111] [ 7]  / answers: 1 / hits: 47388  / 15 Years ago, mon, march 23, 2009, 12:00:00

I have JavaScript which performs a whole lot of calculations as well as reading/writing values from/to the DOM. The page is huge so this often ends up locking the browser for up to a minute (sometimes longer with IE) with 100% CPU usage.



Are there any resources on optimising JavaScript to prevent this from happening (all I can find is how to turn off Firefox's long running script warning)?


More From » javascript

 Answers
10

if you can turn your calculation algorithm into something which can be called iteratively, you could release control back the browser at frequent intervals by using setTimeout with a short timeout value.



For example, something like this...



function doCalculation()
{
//do your thing for a short time

//figure out how complete you are
var percent_complete=....

return percent_complete;
}

function pump()
{
var percent_complete=doCalculation();

//maybe update a progress meter here!

//carry on pumping?
if (percent_complete<100)
{
setTimeout(pump, 50);
}
}

//start the calculation
pump();

[#99807] Monday, March 16, 2009, 15 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
aileent

Total Points: 556
Total Questions: 107
Total Answers: 101

Location: Croatia
Member since Fri, Sep 11, 2020
4 Years ago
;