close

How to measure time elapsed on Javascript?

Hello Guys, How are you all? Hope You all Are Fine. Today we are going to learn How to measure time elapsed on Javascript? in javascript. So Here I am Explain to you all the possible methods here.

Without wasting your time, Let’s start This Article.

How to measure time elapsed on Javascript?

  1. How to measure time elapsed on Javascript ?

    to measure time elapsed on Javascript var startTime, endTime;
    function start() {
    startTime = new Date();
    };
    function end() {
    endTime = new Date();
    var timeDiff = endTime – startTime; //in ms
    // strip the ms
    timeDiff /= 1000;
    // get seconds
    var seconds = Math.round(timeDiff);
    console.log(seconds + ” seconds”);
    }

  2. How to measure time elapsed on Javascript ?

    to measure time elapsed on Javascript var startTime, endTime;
    function start() {
    startTime = new Date();
    };
    function end() {
    endTime = new Date();
    var timeDiff = endTime – startTime; //in ms
    // strip the ms
    timeDiff /= 1000;
    // get seconds
    var seconds = Math.round(timeDiff);
    console.log(seconds + ” seconds”);
    }

Method 1

The Date documentation states that :

The JavaScript date is based on a time value that is milliseconds since midnight January 1, 1970, UTC

Click on start button then on end button. It will show you the number of seconds between the 2 clicks.

The milliseconds diff is in variable timeDiff. Play with it to find seconds/minutes/hours/ or what you need

var startTime, endTime;

function start() {
  startTime = new Date();
};

function end() {
  endTime = new Date();
  var timeDiff = endTime - startTime; //in ms
  // strip the ms
  timeDiff /= 1000;

  // get seconds 
  var seconds = Math.round(timeDiff);
  console.log(seconds + " seconds");
}
<button onclick="start()">Start</button>

<button onclick="end()">End</button>

 Run code snippetExpand snippet

OR another way of doing it for modern browser

Using performance.now() which returns a value representing the time elapsed since the time origin. This value is a double with microseconds in the fractional.

The time origin is a standard time which is considered to be the beginning of the current document’s lifetime.

Method 2

Summery

It’s all About this article. Hope all method helped you a lot. Comment below Your thoughts and your queries. Also, Comment below which method worked for you? Thank You.

Leave a Comment