Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

JavaScript

why isnt the setInterval function clearing

<!DOCTYPE html>
<html>
    <head>
        <title>test</title>
        <meta charset="utf-8">
        <link rel="stylesheet" href="main.css">
        <style>
            body{text-align: center;}
        </style>
    </head>
    <body>
    <h1>color</h1>
    <button>Click ME!</button>
    <button>Click ME!</button>
    </body>
    <script src=scripts.js></script>
</html>

I have two buttons and when they're clicked they change the h1 color and the innerText to the name of that color then after two seconds the innertext changes to thanks and then is supposed to change back after, but its not changing back. I also just realized something when it does work the thanks message would flash away immediately, any ideas as to how to make this work?

var html= document.children[0];
var body=html.children[1];
var button1=body.children[1];
var button2=body.children[2];
var h1=body.children[0];

function change(element,color,innerText){
    element.style.color=color;
    element.innerHtml=innerText;
    let stop=1;
    let timer=setInterval(function(){element.innerHTML="thanks"; stop=0;}, 2000);
    if(stop===0){clearInterval(timer);  
        element.innerHTML=innerText;
    }

}

button1.addEventListener('click',function(){return change(h1,'blue','blue');})
button2.addEventListener('click',function(){return change(h1,'red','red');})

1 Answer

It never clears because the line "if(stop===0)" executes immediately on change, it doesn't wait around for the interval to execute and set stop to 0 before evaluating.

You might look at javascript's setTimeout method instead of setInterval so you don't have to worry about clearing the interval.