Functions as Parameters


#1

Im trying to go step by step, but I dont even understand the task of Functions as Parameters task (https://www.codecademy.com/courses/introduction-to-javascript/lessons/higher-order-functions/exercises/functions-as-parameters?action=resume_content_item).

Can somebody explaine, what is going on in this code from the task?
const timeFuncRuntime = funcParameter => {
let t1 = Date.now();
funcParameter();
let t2 = Date.now();
return t2 - t1;
}
const addOneToOne = () => 1 + 1;

timeFuncRuntime(addOneToOne);

  1. The Date.now() method returns the number of milliseconds elapsed since January 1, 1970 00:00:00 UTC. (https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/now)
    Why it so neccesary to use such method in this code?

  2. In such case t2 and t1 will have the equal values, so what result we are expecting by t2 - t1?


#2

Your t1 and t2 variables will never contain the same value. The statements are run in succession. t2 will always be a later date in milliseconds than t1. Essentially what you are returning return t2 - t1 is how long it takes for your function funcParameter() to run. The let t1 = Date.now() is like starting a stop watch. It’s recording the exact time in milliseconds since January 1, 1970 00:00:00 right before your function call. After the function has executed, the let t2 = Date.now() is like stopping the stop watch. It’s recording the exact time immediately after the function is finished executing. When you subtract t1 from t2 you get the time elapsed during the execution of funcParameter(). Hopefully that made sense.