You can measure the time elapsed during the execution of TypeScript commands by keeping a reference to the start
time and then subtracting the current
time at any point on your program from that start
time to obtain the duration between two points in time.
const start = new Date().getTime();
// Run some code..
let elapsed = new Date().getTime() - start;
Let's create two helper functions to get the current time (i.e. now
) and the elapsed
time at any moment.
// Returns current time
// (and, if provided, prints the event's name)
const now = (eventName = '') => {
if (eventName) {
console.log(`Started ${eventName}..`);
}
return new Date().getTime();
}
// Store current time as `start`
let start = now();
// Returns time elapsed since `beginning`
// (and, optionally, prints the duration in seconds)
const elapsed = (beginning = start, log = false) => {
const duration = new Date().getTime() - beginning;
if (log) {
console.log(`${duration/1000}s`);
}
return duration;
}
With those utility functions defined, we can measure the duration of different events.
// A promise that takes X ms to resolve
function sleep(ms: any) {
return new Promise(resolve => setTimeout(resolve, ms));
}
// Measure duration (while waiting for 2 seconds)
(async function demo() {
const waitInSeconds = 2;
let beginning = now(`${waitInSeconds}-second wait`);
// Prints Started 2-second wait..
await sleep(waitInSeconds * 1000);
elapsed(beginning, true);
// Prints 2.004s
})();
To avoid warnings, you must set target
to es2015
in your tsconfig.json
.
If you found this useful, you might want to join my mailing lists; or take a look at other posts about code, React, and TypeScript.