Home > Web Front-end > JS Tutorial > body text

Find elapsed time in JavaScript

王林
Release: 2023-08-26 22:33:08
forward
674 people have browsed it

在 JavaScript 中查找经过的时间

Sometimes it needs to find the total time spent performing certain operations in JavaScript. For example, we need to find the total time spent by users updating their profiles.

Additionally, there may be other similar use cases where we need to find the difference between a specific time and the current time and thus find the total elapsed time. Here we will learn various ways to find elapsed time in JavaScript.

Using the Date() object in JavaScript to find elapsed time

In JavaScript, we can use the Date() object constructor to get the current time. It returns the total number of milliseconds since January 1, 1970.

Here, we can get the elapsed time between two dates by the difference in total milliseconds between the two dates.

grammar

Users can use the Date() object constructor according to the following syntax to find elapsed time in JavaScript.

let startTime = new Date();
let endTime = new Date();
let timeElapsed = endTime - startTime;
Copy after login

In the above syntax, first, we get the start time. After that, we took the end time. To get the elapsed time we take the start and end time difference.

Example 1

In the example below, we store the current time in the startTime variable. After that, we call the loopThrough() function. The function executes the loop 6,00,000 times.

After the function execution is completed, we store the current time in the endTime variable. After that, we calculate the difference between endTime and startTime to get the total time spent executing the function.

<html>
<body>
   <h3> Using the <i> Date() object </i> to find the time elapsed in JavaScript </h3>
   <div id="output"> </div>
   <script>
      let output = document.getElementById('output');
      function loopThrough() {
         for (i = 0; i < 600000; i++) {
         
            //Do nothing
         }
      }
      let startTime = new Date();
      loopThrough();
      let endTime = new Date();
      let timeElapsed = endTime - startTime;
      output.innerHTML += "Total time elapsed to loop through 600000 times: " + timeElapsed + " milliseconds.";
   </script>
</body>
</html>
Copy after login

Example 2

The example below shows the time difference between a specific date and the current time. After that, we call the formatDate() function to format the date into day, hour, minute, and second format.

In the formatDate() function, we get the time difference as parameters and the total number of days, hours, minutes and seconds. In the output, the user can check the total time elapsed since December 31, 2019.

<html>
<body>
   <h3> Using the <i> Date() object </i> to find the time elapsed in JavaScript </h3>
   <div id="output"></div>
   <script>
      let output = document.getElementById('output');
      function formatDate(difference) {
      
         //Arrange the difference of date in days, hours, minutes, and seconds format
         let days = Math.floor(difference / (1000 * 60 * 60 * 24));
         let hours = Math.floor((difference % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
         let minutes = Math.floor((difference % (1000 * 60 * 60)) / (1000 * 60));
         let seconds = Math.floor((difference % (1000 * 60)) / 1000);
         output.innerHTML += "Total time elapsed is: " + days + " days " + hours + " hours " + minutes + " minutes " + seconds + " seconds.";
      }
      let start = new Date("December 31, 2020 23:59:59");
      let end = new Date();
      let difference = end - start;
      formatDate(difference);
   </script>
</body>
</html>
Copy after login

Use Console.time() function

The console.Time() method takes a label as a parameter. Whenever we call the console.time() method using a certain label, it starts counting time.

The console.timeEnd() method takes the same label that we passed as the console.time() method parameter and prints the elapsed time since the console.time() method was called.

grammar

Users can use the console.time() function according to the following syntax to find the total time used in JavaScript.

console.time(label);
console.timeEnd(label);
Copy after login

In the above syntax, the console.time() and console.timeEnd() methods take the same label.

Example 3

In the following example, first, we execute the console.time() method while passing the "execution time" label as a parameter. After that, we call the loop 1,00,000 times. Next, we call the console.timeEnd() method using the same label to print the total elapsed time in the console.

// use the console.time() function to find the time elapsed
console.time('Execution time');
for (let i = 0; i < 100000; i++) {
   // Iterating through the loop
}
console.timeEnd('Execution time');
Copy after login

Use Performance.now() method

Users can use the Performance.now() method to get the total time spent executing JavaScript code. It returns the elapsed time in milliseconds.

grammar

Users can use the Performance.now() method according to the syntax below to find the elapsed time in JavaScript.

let startTime = performance.now();
let endTime = performance.now();
let timeElapsed = endTime - startTime;
Copy after login

We calculated the difference between the start time and the end time in the above syntax.

Example 4

In the example below, we use the Performance.now() method when the JavaScript code starts executing. After that, we set the time to 1000 milliseconds using the setTime() method.

Once it times out, it will execute the callback function, which will call the Performance.now() method again and get the difference between startTime and endTime to find the total running time.

<html>
<body>
   <h3> Using the <i> performance.now() method </i> to find the time elapsed in JavaScript </h3>
   <div id="output"></div>
   <script>
      let output = document.getElementById('output');
      let startTime = performance.now();
      setTimeout(function () {
         let endTime = performance.now();
         let timeElapsed = endTime - startTime;
         output.innerHTML = 'Time elapsed: ' + timeElapsed + ' milliseconds';
      }, 1000);
   </script>
</body>
</html>
Copy after login

Conclusion

Users learned three ways to find elapsed time in JavaScript. The first way is to use a Date() object. The second way is to use console.time() and console.timeEnd() methods, which always prints the time in the console. The third method is to use the Performance.now() method.

The above is the detailed content of Find elapsed time in JavaScript. For more information, please follow other related articles on the PHP Chinese website!

source:tutorialspoint.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template