Measure time with a higher order utility function
Luka Vidaković

Luka Vidaković @apisurfer

About: Software eng. with a decade of experience.

Location:
Croatia, Zagreb
Joined:
Sep 25, 2019

Measure time with a higher order utility function

Publish Date: Mar 2 '20
8 4

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!

Comments 4 total

Add comment