Search code examples
javascriptfunctiontimerclosures

How to write timer function correctly?


I have several complex sort functions that take parameters from other functions I want to write a timer function that will take a complex function with parameters, which call look smthng this:

timer(sortFunc1(arrayGenerator(COUNT), arg1...,))
timer(sortFunc2(arrayGenerator(COUNT), arg1...,))
...
timer(sortFunc10(arrayGenerator(COUNT), arg1...,))

but my timer function throw 'func is not a function':

function timer(func) {
   let start = Date.now();
   func();
   console.log(Date.now() - start);
}

How I should write function timer to call it like way above?

I've tried reading articles about complex functions, returning a function from a function


Solution

  • You need to pass the function itself (without parentheses) and its arguments separately, and then use the apply method to call the function with the provided arguments:

    function timer(func, ...args) {
       let start = Date.now();
       func.apply(null, args);
       console.log(Date.now() - start);
    }
    

    And this is how you use it:

    timer(sortFunc1, arrayGenerator(COUNT), arg1, ...);
    timer(sortFunc2, arrayGenerator(COUNT), arg1, ...);
    // ...
    timer(sortFunc10, arrayGenerator(COUNT), arg1, ...);