This function
const catchingEggs = () => {
myInterval = setInterval(function(){
//if(speed >= 25) speed = 500 - score*15;
if(eggBrokenLeft.style.visibility === "visible" || eggBrokenRight.style.visibility === "visible") {
clearInterval(myInterval);
return
}
fallingEggs(allEggs[Math.floor(Math.random()*4)], speed);
}, speed*3);
}
works fine, as long as the second parameter of setInterval() doesn't change (for example speed*3, but if i uncomment if(speed >= 25) speed = 500 - score*15; it will only work if i lose within the first 3 intervals (until score reach 3), but if i keep playing and lose later (that's eggBrokenLeft.style.visibility === "visible" || eggBrokenRight.style.visibility === "visible", part which should trigger clearInterval), nothing happens, the game just keeps playing.
I want to be able to increase the speed, WHILE in the interval and still be able to stop that interval. I guess I could write different intervals for different speeds and somehow put them together, but it would be messy, plus I want to be able to increase speed gradually, depending on the score.
An alternative way to implement an accelerating loop might be to use recursion on a function that executes commands within a setTimeout block. setTimeout has the advantage in this situation as it only executes once each time it is called and so intervals can be adjusted for each loop.
A conditional check within the timeout function determines whether to repeat the cycle, by making a call to the parent function, or whether to end repetition, by doing nothing. The interval applied to the timeout can be modified each time the function is executed.
This snippet demonstrates the principle by repeating a console log with increasing frequency until a specified minimum interval value is reached.
let speed = 1000;
run();
function run() {
setTimeout(function(){
console.log(speed);
if (speed > 200) {run()}; // repeat only if condition met;
},speed-=50); // end timeout block;
}; // end function;
You might be able to apply your logic to this framework to achieve the effect you want.