Before I reach for a profiler I want a quick number: how long does this loop or this request take? console.time() is a stopwatch you can start and stop in two lines.
Give the timer a label, run your code, and stop it with the same label:
console.time("fetchData");
await fetch("https://example.com/api/items");
console.timeEnd("fetchData");
// fetchData: 123.456ms (example output)
console.timeLog() prints the elapsed time without stopping the timer. You can add extra values, which is useful inside a loop:
console.time("import");
for (const row of rows) {
await save(row);
console.timeLog("import", "saved " + row.id);
}
console.timeEnd("import");
Labels let you run several timers at once. Without a label, the name is default.
Caveats: starting a timer with a label that is already running does not restart it. Browsers log a warning, so call timeEnd() first. The same warning appears when you stop a label that never started, which usually means a typo.
The result is a printed string, not a value you can use in code, and it measures wall-clock time including waiting. For numbers you want to store or compare, MDN points to performance.mark() and performance.measure().
It works in browsers, in Node and in web workers. Remove the calls before shipping, since they only add noise to a visitor’s console.
Further reading: MDN: console.time()