JavaScript JavaScript and the DOM Responding to User Interaction Events and Functions as Parameters Review

Hanwen Zhang
Hanwen Zhang
15,509 Points

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

Peter Vann
Peter Vann
36,049 Points

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!

Peter Vann
Peter Vann
36,049 Points

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!