Javascript Heap Out Of Memory Error
Solution 1:
I don't think this does what you would expect. setTimeout
takes the function that you pass it and after the delay, adds the function to the stack after everything else thats there. Since the while loop blocks, you end up with a weird situation where the delayed function won't get called until the while loop finishes.
var x = 0;
while (x<10) {
x++;
console.log('omg');
setTimeout(function(){console.log('from timeout');},0);
}
What you will see above is that the loop will continue until it's done before any of the setTimeouts
execute. If your loop is infinite then it creates a huge stack of calls that need to happen in the future but can't because they are blocked by the loop.
If I had to guess, it seems like you are implementing some sort of long polling thing. if that thing is synchronous (seems like it isn't) it could be easier to poll it. If it's not, then you will have to think about handling this asynchronously. Either with callbacks, events or promises.
In a situation where you are waiting for something to happen events are often your friend. You can create custom events or use frameworks to help propagate for you.
Solution 2:
If that i = i+1;
in the delayed function is the only place in your code where i
is changed, that would probably explain it. Your code will keep repeating and creating timers for setTimeout
thousands of times since i
can only change(which will advance the loop) 3 seconds later(assuming the timer isn't then delayed by the load from all the timers being created, which it probably will be).
You need to refactor this code to not use setTimeout
in a loop.
Solution 3:
Based on KarlReids answer ( good explanation) you may want to try this:
var i=0;
while( typeof(apiResults[0].league.season.eventType[0].events[0].pbp[i].pbpDetails[p]) == 'undefined' && i<=apiResults[0].league.season.eventType[0].events[0].pbp.length) {
setTimeout(function(i){//notice the bound i...if( typeof(apiResults[0].league.season.eventType[0].events[0].pbp[i+1].pbpDetails[0]) != 'undefined') {
//some code
}
}, 3000,i);
i = i+1;//increase in the main loop
}
Or recursive ( one timeout after another):
(functionloop(i){
if( typeof(apiResults[0].league.season.eventType[0].events[0].pbp[i].pbpDetails[p]) == 'undefined' && i<=apiResults[0].league.season.eventType[0].events[0].pbp.length) {
setTimeout(function(i){//notice the bound i...if( typeof(apiResults[0].league.season.eventType[0].events[0].pbp[i+1].pbpDetails[0]) != 'undefined') {
//some code
}
//nextloop(i+1);
}, 3000,i);
}
})(0);//start with zero
Post a Comment for "Javascript Heap Out Of Memory Error"