Reputation: 982
nowadays i am optimizing some js code.
there is a function named appendXYZ,and it is invoked in a loop with other functions.
it looks like as the following:
function OuterFunc (){
for(...){// about 150 times
...
appendXYZ();
//other dependent functions
...
}
}
and now i am pretty sure that appendXYZ cause high cpu usage - it can reach 50%,
but if i remove this function,cpu usage is only 1%.
when the cpu usage is 50%,the browser is nearly frozen and the page is lack of responsiveness.
what is more ,the OuterFunc execute every 20 seconds and appendXYZ is from a third party script code and i cant modify it.
so how to optimize this code?
now i am trying to use setTimeout but i dont know whether it works.
Upvotes: 1
Views: 4403
Reputation: 41533
A possibility is that the OuterFunc
execution time is bigger that it's repetition interval.
In other words, the OutherFunc
takes longer than 20 milliseconds to execute and being called every 20 seconds it will produce a stackoverflow exception because the function is being called before it finished it's execution in an infinite loop.
If you are using setInterval
to execute the OuterFunc
function every 20 milliseconds, this can be fixed by using setTimeout
calls to simulate the setInterval
function :
(function helper(){
OutherFunc();
// after the OutherFunc is done executing, trigger it after 20 milliseconds
setTimeout(helper, 20);
})();
This might help you only if the setInterval
is the cause of the browser freeze.
If this doesn't help you and if you don't care that much about old browsers, maybe you could implement a sort of "threading" using web-workers. This way your code gets executed in different threads which will definitely speed up your app (a.k.a bye bye browser freeze).
Hope this helps!
Upvotes: -1
Reputation: 22668
If there's nothing you can do to optimize the actual code, you can spread around the execution of the loop iterations to keep the browser responsive. According to Robert Miller's paper, the maximum amount of time you can hold up a UI and still have it feel responsive to the user is 100 milliseconds. For a technique of how to do this using setTimeout
see UI responsiveness and javascript.
Upvotes: 0
Reputation: 322502
I don't know what that function does, but you could try making its invocation asynchronous.
It may or may not work, and it will still require the same amount of CPU, but it should at least free up the browser a bit.
function OuterFunc (){
for( var i = 0; i < 150; i++ ){
// ...
setTimeout( appendXYZ, 0 );
//other dependent functions
// ...
}
}
Again this may break the function. Can't tell without seeing more code.
If you're passing arguments, then you'd need something like:
function invoker( j ) {
return function() {
appendXYZ( j );
};
}
function OuterFunc (){
for( var i = 0; i < 150; i++ ){
// ...
setTimeout( invoker( i ), 0 );
//other dependent functions
// ...
}
}
Upvotes: 2