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

Trying to implement a delay

ok so i have a dive named "thestar" with two classes which i toggle, so on click the div will have the class "sun", and on click again the class will be "moon"

var counterStar = 0; intervalStar = setInterval(function() {

    if (counterStar < 5 && $(thestar).hasClass("moon")) {
        $(".stars").append('<p class="star' + counterStar + '"' + ' ></p>');
        counterStar++;
    }

},3000);

if($(thestar).hasClass("sun"))
{
    counterStar=0;
    clearInterval(intervalStar);
}

i add 5 paragraphs at a interval of 3 seconds

//i delete the paragraphs when the class is sun

problem: if i toggle between classes more than once, the paragraphs will be added very fast, it wont take into account the 3 seconds

1 Answer

I would add a check to the

if($(thestar).hasClass("sun"))

clause to make sure the 3 seconds has completed.