CodeBlanks Logo Icon CodeBlanks

Timing with console.time

JavaScript course · Beginner · Lesson 115/133

Learn to measure an operation's duration with console.time and timeEnd.

Timing with console.time

With console.time and console.timeEnd you can measure an operation's duration. The time and timeEnd pair with the same label (string) prints the elapsed time in milliseconds.

Example: console.time("loop"); for (...) {} console.timeEnd("loop");. The output looks like loop: 1.234ms. If the labels do not match no time is printed; so it is important to use the same label.

Label matching and multiple timings

console.time and console.timeEnd must match with the same label string. If you use different labels no measurement is made; the browser may warn about the unmatched label.

If you want several measurements you can use different labels: console.time("a"); console.time("b"); ... console.timeEnd("a"); console.timeEnd("b");. This way each measurement stays independent and you can see how long each operation took. Starting the same label twice may give unexpected results.

Exercise Measure a loop's duration

Start a timer with console.time("loop"). Run an empty loop with for (let i = 0; i < 100; i++) {}. Then print the duration with console.timeEnd("loop").

Show example solution
console.time("loop");
for (let i = 0; i < 100; i++) {
  // empty loop
}
console.timeEnd("loop");

Test yourself

  1. What does console.timeEnd("a") do?

    console.time("a");
    // ...
    console.timeEnd("a");
    • It only prints "a"
    • It prints the elapsed time for label "a" in milliseconds
    • It resets the timer
    • It does nothing
    Show answer

    It prints the elapsed time for label "a" in milliseconds — Correct. timeEnd ends the measurement started by time and prints the duration.

  2. Print an intermediate value

    console.time("işlem");
    // işlem burada
    console.____("işlem bitti");
    console.timeEnd("işlem");
    Show answer
    console.time("işlem");
    // işlem burada
    console.log("işlem bitti");
    console.timeEnd("işlem");
  3. Match the method to its behavior

    console.time
    Starts a timer
    console.timeEnd
    Stops the timer and prints the duration
    console.timeLog
    Prints an intermediate time
    console.log
    Prints a value

All lessons in Beginner