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 Callback Functions in JavaScript Callbacks with Timers Triggering an Animation

Added setInterval(startAnimation, 2000); Error: startAnimation should be called only once.

We have a function startAnimation. The startAnimation function should be triggered 2 seconds after the page loads. Update the code to do this. Don't use an anonymous function.

app.js
const section = document.getElementById("animateMe");

function startAnimation() {
  //Applies spinning animation to section element
  section.className = "spin";
}

setInterval(startAnimation, 2000);
index.html
<!DOCTYPE html>
<html lang="en">
    <head>
        <title></title>
        <link rel='stylesheet' href='styles.css'>
    </head>
    <body>
        <section id="animateMe">
            <p>Animate Me in 2 Seconds!</p>
        </section>
        <script src='app.js'></script>
    </body>
</html>

2 Answers

Jennifer Nordell
seal-mask
STAFF
.a{fill-rule:evenodd;}techdegree
Jennifer Nordell
Treehouse Teacher

Hi there! Adding a setInterval causes something to happen at intervals. In this case, it is happening every 2 seconds which means that the startAnimation is being called every 2 seconds. The function you're looking for is setTimeout. I feel like you can get it with this hint, but let me know if you're still stuck! :sparkles:

The task is requiring that "The startAnimation function should be triggered 2 seconds after the page loads." Setting a SetInterval method would cause multiple occurrences of this function in a period of 2seconds. Whereas the SetTimeout method will trigger an initial 2sec delay after the page loads. Hope that helps ;)

const section = document.getElementById("animateMe");

function startAnimation() { //Applies spinning animation to section element section.className = "spin"; } setTimeout(startAnimation, 2000);