DEV Community

Luka Vidaković
Luka Vidaković

Posted on

Measure time with a higher order utility function

I consider closures and higher order functions to be one of the most powerful language features, if not the most powerful. Here is a 2-liner function that uses both of them. Comes in handy for testing, debugging and measuring performance of some chunks of code.

/*
* startTimer creates a function that returns time difference in milliseconds
*/
function startTimer() {
  const startTime = new Date()
  return () => new Date() - startTime
}
Enter fullscreen mode Exit fullscreen mode

Example of usage:

const getTimeDifference = startTimer()

// Should output a number around 3000 after 3 seconds have passed
setTimeout(() => {
  console.log(`${getTimeDifference()} milliseconds have passed!`)
}, 3000)
Enter fullscreen mode Exit fullscreen mode

This allows you to start tracking multiple events at any given time and retrieve the time difference whenever it's required.

Cheers!

Top comments (4)

Collapse
 
patarapolw profile image
Pacharapol Withayasakpunt • Edited

You should also consider using performance.now().

Collapse
 
apisurfer profile image
Luka Vidaković

Hey, thanks for mentioning this! I haven't had a clue that this API exists. I mostly use the proposed function in Nodejs, but this will come in handy on the client side :)

Collapse
 
patarapolw profile image
Pacharapol Withayasakpunt • Edited

For Node.js, it is inside perf_hooks.

I have wrote js-benchmark some time ago, that works in both Node.js and browsers.

Thread Thread
 
apisurfer profile image
Luka Vidaković

Seems like it's time to brush up on my knowledge of the existing browser and node APIs 😅