Reputation: 3
I need this code to iterate for about 10 seconds (or better indefinitely) without causing javascript maximum stack size. I have comented setInterval because it's causing the problem!
var myToggle = false;
function myFunc () {
setTimeout(function () {
if (myToggle) {
console.log("red");
}
else {
console.log("yellow");
}
myToggle = !myToggle;
}, 500);
// setInterval(myFunc, 10000);
}
myFunc();
Upvotes: 0
Views: 66
Reputation: 3932
This usually a sign of bad design but the solution may be the following:
var myToggle = false;
function myFunc () {
var startTime = new Date()/1;
function wait () {
if (myToggle) {
console.log("red");
} else {
console.log("yellow");
}
myToggle = !myToggle;
if (new Date() < startTime + (10*1000)) { // exit condition
setTimeout(wait, 500);
}
}
wait();
}
myFunc();
FYI: Infinite callbacks, among the other things, slowdown the browser and consume battery on mobile devices.
Upvotes: 0
Reputation: 1378
Call setInterval instead. setTimeout will call the inner function once. setInterval will continue calling until you cancel.
Upvotes: 1