-1

I am trying to add a feature to my game where an img appears after a set amount of time. The is only displayed for a set time before it disappears again or until it is clicked.

Here is my code below but it doesn't work because the clearInterval is ending the disappear function before it executes. But without it, the timer continues and the image appears and disappears at the same time.

How would I make it so the image stays for 5 seconds, then disappears again, then next time the image appears it stays for 5 seconds again?

const bunnyRocket = document.getElementById('bunny-rocket');
bunnyRocket.hidden = true;

bunnyRocket.addEventListener('click', () => {
    console.log('You got it');
    player.carrots += 1000;
    bunnyRocket.hidden = true;
})

const rocketAppear = setInterval(bunnyRocketAppear, 5000);
function bunnyRocketAppear() {
    let disappear = setInterval(() => {
        console.log('DISAPPEAR');
        bunnyRocket.hidden = true;
    }, 5000)

    console.log('SHOULD APPEAR NOW');
    bunnyRocket.hidden = false;

    clearInterval(disappear);
}
Owen
  • 13
  • 4
  • So the image is supposed to constantly appear and disappear again, and the re-appearing happens automatically, not triggered by a click anywhere or something? Then why clear the interval to begin with? All you need to do is toggle between shown and hidden. – CBroe Oct 19 '22 at 13:34
  • @CBroe It appears, stays visable for a set time then disappears again. I am using this to add a clickable item which gives the player extra "points". So it only shows up every once in a while then when it does appear, it doesn't stay forever. – Owen Oct 19 '22 at 13:48

1 Answers1

0

Your bunny appears every 5 seconds but also disappears after 5 seconds. You might want to make your bunny disappear before he appears again (e.g make him disappear after 3s).

Additionally, since the bunny only disappears once for every time he appears, you'd want your second interval to be a timer instead

const bunnyRocket = document.getElementById('bunny-rocket');
bunnyRocket.hidden = true;

bunnyRocket.addEventListener('click', () => {
    console.log('You got it');
    player.carrots += 1000;
    bunnyRocket.hidden = true;
})

const rocketAppear = setInterval(bunnyRocketAppear, 5000);
function bunnyRocketAppear() {
    //everytime he appears, set a timeout to make him disappear after 3s
    let disappear = setTimeout(() => {
        console.log('DISAPPEAR');
        bunnyRocket.hidden = true;
    }, 3000)

    console.log('SHOULD APPEAR NOW');
    bunnyRocket.hidden = false;

    //If we do clearTimeout(disappear), the bunny won't disappear :(
}
BlobKat
  • 88
  • 1
  • 8