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);
}
>Solution :
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 :(
}