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

Hi, setTimeout() is not working in my project

Hi, I'm trying to delay the changing of content inside my h2 and parapgraph elements and I'm using setTimeout function to achieve this. Here is the code from the JavaScript file:

const title = document.querySelector("h2");
const question = document.querySelector("p");

function changeQuestion(number, question) {
  title.textContent = "Question #" + number;
  question.textContent = question;
}


//The part below runs after pressing the button
    $("h2, p, .container-btn").fadeOut(500);
    setTimeout(
      changeQuestion("1", "What is?"), 1000
    );

The text content is changing immediately when the elements are fading out, what is wrong with this code? Thank you for the answer :)

1 Answer

I don't see how the text content for your paragraph will change since your parameter question in the changeQuestion function has the same name used for the const declaration above const question = document.querySelector("p");

I changed it to:

function changeQuestion(number, q) {
  title.textContent = "Question #" + number;
  question.textContent = q;
}

and then it changed.

As far as the immediate change here is a good read. Look for 'Pass a function, but don’t run it' where it is explained that by including the brackets your function is executed immediately and the result is passed to setTimeout. Since the function returns nothing, nothing is scheduled.

Use this instead:

setTimeout(changeQuestion, 1000, "1", "What is?");