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!
Top comments (4)
You should also consider using performance.now().
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 :)
For Node.js, it is inside perf_hooks.
I have wrote js-benchmark some time ago, that works in both Node.js and browsers.
Seems like it's time to brush up on my knowledge of the existing browser and node APIs 😅