How to Use console.time in JavaScript for Simple Performance Timing
Use
console.time(label) to start a timer with a unique label and console.timeEnd(label) to stop the timer and print the elapsed time in milliseconds. This helps you measure how long a block of code takes to run in JavaScript.Syntax
The console.time(label) method starts a timer with the given label. The console.timeEnd(label) method stops the timer with the same label and logs the elapsed time in milliseconds to the console.
The label is a string that identifies the timer. You must use the same label to start and stop the timer.
javascript
console.time('myTimer'); // code to measure console.timeEnd('myTimer');
Example
This example shows how to measure the time taken to run a loop that counts to 1 million. The timer starts before the loop and ends after it, printing the elapsed time.
javascript
console.time('loopTimer'); let sum = 0; for (let i = 0; i < 1000000; i++) { sum += i; } console.timeEnd('loopTimer');
Output
loopTimer: X ms
Common Pitfalls
- Using different labels for
console.timeandconsole.timeEndwill cause the timer not to stop or print. - Calling
console.timeEndwithout a matchingconsole.timewill show a warning or error in the console. - Starting multiple timers with the same label before stopping the first one can cause confusion.
javascript
console.time('test'); // some code console.timeEnd('wrongLabel'); // This will not stop the 'test' timer // Correct way: console.time('test'); // some code console.timeEnd('test');
Quick Reference
| Method | Description |
|---|---|
| console.time(label) | Starts a timer with the given label. |
| console.timeEnd(label) | Stops the timer with the given label and logs elapsed time. |
| label | A string identifier for the timer; must match in both methods. |
Key Takeaways
Use console.time and console.timeEnd with the same label to measure code execution time.
Labels must match exactly to start and stop timers correctly.
console.timeEnd prints the elapsed time in milliseconds to the console.
Avoid starting multiple timers with the same label without stopping them first.
Use console.time for quick and simple performance checks in JavaScript.