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;
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 id="Using-the-i-Date-object-i-to-find-the-time-elapsed-in-JavaScript"> 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>
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 id="Using-the-i-Date-object-i-to-find-the-time-elapsed-in-JavaScript"> 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>
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);
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');
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;
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 id="Using-the-i-performance-now-method-i-to-find-the-time-elapsed-in-JavaScript"> 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>
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!

Detailed explanation of JavaScript string replacement method and FAQ This article will explore two ways to replace string characters in JavaScript: internal JavaScript code and internal HTML for web pages. Replace string inside JavaScript code The most direct way is to use the replace() method: str = str.replace("find","replace"); This method replaces only the first match. To replace all matches, use a regular expression and add the global flag g: str = str.replace(/fi

This tutorial shows you how to integrate a custom Google Search API into your blog or website, offering a more refined search experience than standard WordPress theme search functions. It's surprisingly easy! You'll be able to restrict searches to y

This article series was rewritten in mid 2017 with up-to-date information and fresh examples. In this JSON example, we will look at how we can store simple values in a file using JSON format. Using the key-value pair notation, we can store any kind

So here you are, ready to learn all about this thing called AJAX. But, what exactly is it? The term AJAX refers to a loose grouping of technologies that are used to create dynamic, interactive web content. The term AJAX, originally coined by Jesse J

Enhance Your Code Presentation: 10 Syntax Highlighters for Developers Sharing code snippets on your website or blog is a common practice for developers. Choosing the right syntax highlighter can significantly improve readability and visual appeal. T

Leverage jQuery for Effortless Web Page Layouts: 8 Essential Plugins jQuery simplifies web page layout significantly. This article highlights eight powerful jQuery plugins that streamline the process, particularly useful for manual website creation

This article presents a curated selection of over 10 tutorials on JavaScript and jQuery Model-View-Controller (MVC) frameworks, perfect for boosting your web development skills in the new year. These tutorials cover a range of topics, from foundatio

Core points This in JavaScript usually refers to an object that "owns" the method, but it depends on how the function is called. When there is no current object, this refers to the global object. In a web browser, it is represented by window. When calling a function, this maintains the global object; but when calling an object constructor or any of its methods, this refers to an instance of the object. You can change the context of this using methods such as call(), apply(), and bind(). These methods call the function using the given this value and parameters. JavaScript is an excellent programming language. A few years ago, this sentence was


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Dreamweaver Mac version
Visual web development tools

Safe Exam Browser
Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

Zend Studio 13.0.1
Powerful PHP integrated development environment

SAP NetWeaver Server Adapter for Eclipse
Integrate Eclipse with SAP NetWeaver application server.

SublimeText3 English version
Recommended: Win version, supports code prompts!
