console.time and console.timeEnd
You'll learn how to measure exactly how long specific code blocks take to execute using labeled performance timers.
What Are console.time and console.timeEnd?
Think of these methods as a stopwatch for your code. You start the timer with a label, run your code, then stop the timer with the same label—and the console displays how much time elapsed. It's perfect for identifying performance bottlenecks and comparing different approaches to the same problem.
How It Works
You call console.time() with a string label to start tracking, then call console.timeEnd() with the same label to stop and display the result:
console.time('data-processing');
// Simulate some data processing work
let result = 0;
for (let i = 0; i < 1000000; i++) {
result += i;
}
console.timeEnd('data-processing');
// Output: data-processing: 3.847ms
Using Multiple Timers
You can run multiple timers simultaneously with different labels, which is incredibly useful for comparing nested operations:
console.time('total-operation');
console.time('fetch-data');
// ... fetch operation
console.timeEnd('fetch-data');
console.time('process-data');
// ... processing logic
console.timeEnd('process-data');
console.timeEnd('total-operation');
Each timer is independent, tracked by its unique label string.
Practical Use Cases
Use console.time() when you need to:
- Compare performance of two algorithms
- Identify which function in a chain is slowest
- Measure API response times during debugging
- Validate that optimizations actually improve speed
Key Takeaway: console.time() and console.timeEnd() create labeled stopwatches for measuring code execution time, helping you pinpoint exactly where performance issues occur with millisecond precision.