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
}

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)

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

Cheers!

 
Share this