Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

SetInterval, clearInterval – How to display image for set time then make it disappear

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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 :(
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading