-1

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://github.com/chylinski82/eggs / https://chylinski82.github.io/eggs/

Lissy93
  • 4,181
  • 4
  • 32
  • 55
chylinski
  • 1
  • 4
  • 3
    If you assign your set timeout to a variable, then you can use `clearTimeout` to stop it. – Lissy93 May 13 '22 at 10:13
  • `I tried using clearTimeout() and that doesn’t work either, unless i’m not using it right.` show us how you tried clearTimeout – sojin May 13 '22 at 10:20
  • that's how i used clearTimeout() it doesn't do anything there. i assigned setTimeout() to a variable: `myTimeout = setTimeout(function() { arr[i].style.visibility = 'visible'; }, timeDelay);` and then put it inside the other setTimeout in the conditional: `setTimeout(function() { if(i===3 && position === fallingEggIndex) { clearTimeout(myTimeout); return score } arr[i].style.visibility = 'hidden'; }, timeDelay);` . – chylinski May 13 '22 at 11:49

0 Answers0