Reputation: 261
In the following code, why is it that it could create a possible infinite recursion, and why does the memory usage keep raising, and how to solve it ?
function waitForKeyElements (selectorTxt, actionFunction) {
if (getElementByXPath(selectorTxt) == null) {
var timeControl = setInterval (function () {
waitForKeyElements (selectorTxt, actionFunction);
},
300
);
} else {
clearInterval (timeControl);
actionFunction();
}
}
Upvotes: 0
Views: 113
Reputation: 66673
The variable timeControl
is local to each invocation of the function waitForKeyElements()
- i.e. the timeControl
you set will not be the timeControl
you clear. In other words, the timer you started with setInterval
will never get cleared.
Moving it outside the function should solve it.
i.e.
var timeControl = -1;
function waitForKeyElements (selectorTxt, actionFunction) {
if (getElementByXPath(selectorTxt) == null) {
timeControl = setInterval (function () {
waitForKeyElements (selectorTxt, actionFunction);
},
300
);
} else {
if(timeControl !== -1) clearInterval (timeControl);
actionFunction();
}
}
Also, as user Prinzhorn pointed out in the comment, starting a timer with setInterval in each invocation is bound to be troublesome. You should really be just doing a setTimeout to ensure things don't get out of hand.
Upvotes: 2