I don't know how to stop a function that uses setTimeout()

hi everyone, i’m trying to make a simple game in html/css/js and i’m stuck with setTimeout() in js. because setTimeout(), if i understand well, doesn’t execute immediately when invoked, i can’t find a way to stop it, for example, in case of an event.

In the following snippet:

const fallingEggs = (arr, speed) => {
    let timeDelay = 0;
    for(let i=0; i<arr.length; i++) {
        if(i===3 && position === fallingEggIndex) {
            score++;
            return score
        } else {
            setTimeout (function() {
                arr[i].style.visibility = 'visible';        
                }, timeDelay);
            timeDelay += speed;
            setTimeout(function() {
                arr[i].style.visibility = 'hidden';
                }, timeDelay);
            timeDelay += speed/10;
        }
        
    }   
}

the part if(i===3 && position === fallingEggIndex) doesn’t do what it supposed to do, meaning to stop the execution, update and return score.
I tried using clearTimeout() and that doesn’t work either, unless i’m not using it right.
i’ve been thinking about it all day and my google searches don’t give me what i’m looking for.

full project at https://chylinski82.github.io/eggs/

setTimeout() - Web APIs | MDN

i’ve read it but there must be something that i’m missing. i declared a variable myTimeout which i assigned to setTimeout() function and then i tried to call clearTimeout, if conditions were met. nothing.

Have you searched for and studied any examples? Is there any advice with regard to usage in a loop?

Perhaps work on a small side demonstration to explore the workings.

thanks, that was helpful.

1 Like