brewedbits.dev

Personal blog with guides and news on selfhosting, Linux and AI, from the Netherlands

nextDash nextdash --aboutYour bookmarks. Your terminal. checks your links knows your Docker host one container, no cloudLive demo →nextdash.cc ↗

Tip: console.time() and timeLog() measure how long a piece of code takes

Web-Development
~/tips/tip-javascript-console-time

console.time("fetchData");

Prints how long code took between two labelled console calls.

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()

More Web-Development tips ab -n 200 -c 10 https://example.com/ console.assert(items.length > 0, 'cart is empty', items) document.designMode = "on" function save(item) { Save draft All Web-Development tips (67) All topics

Link