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 JavaScript and the DOM (Retiring) Responding to User Interaction Events and Functions as Parameters Review

How would you set the following function `add` up to run after 5 seconds pass, using Window.setTimeout? In addition, how

How would you set the following function add up to run after 5 seconds pass, using Window.setTimeout? In addition, how would you pass add the arguments 2 and 2 when it runs?

Please help, I don't understand the answer to this question

2 Answers

By the way,

I came up with this code example to illustrate the callback function/parameters relationship better:

const square = function(num) {
  return num * num;
}

const quad = function(func, num) { // func is the callback function
  return func(num) * func(num); // parameters passed to the callback function here
}

console.log( quad(square, 3) ); // square is the callback function passed in

Which will log 81 to the console.

I hope that helps.

Stay safe and happy coding!

Thank you Peter

Hi Hanwen!

The answer is:

window.setTimeout(add, 5000, 2, 2);

Because the first argument to setTimeout is a callback function.

The second argument is the duration of the delay in milliseconds (5 seconds).

The rest of the arguments are any parameters required by the add callback function.

I would have to admit that the order of parameters is not necessarily intuitive, but it's just how the authors of JavaScipt decided they should be!?!

It's kind of odd syntax, if you ask me, and tends to confuse people all the time, so don't feel bad!?! LOL

A lot of people can't understand how the parameters get passed to the callback function, but just trust that they do behind the scenes, if that makes sense!?!

More info:

https://www.w3schools.com/jsref/met_win_settimeout.asp

I hope that helps.

Stay safe and happy coding!