Skip to content

ThirteeNov

My personal blog about coding and internet

Menu
  • About me
  • About Zofia Kreasi
  • Cart
  • Checkout
  • Making an airplane game from scratch in Unity
  • My account
  • Privacy Policy
  • Privacy Policy – zkLeaderboard
  • Sample Page
  • Shop
  • Tutorials on Learning JavaScript
  • ZKAccounts – Privacy Policy
Menu

Counting how much time elapsed using JavaScript

Posted on February 22, 2017August 4, 2020 by Habibie

If we have two variables A and B, and the both of their values is time, how do we measure the distance between those variables?

In other word, let’s say variable A is 6 o’clock and B is 9 o’clock. So between 6 and 9 is 3 hours distance and we know that by subtracting 6 from 9.

In JavaScript we can do that too. Here is simple basic way to calculate a time interval between two variables.

I have two variable in this example. First called “starttime” and its value is the time my document loaded on browser. The second variable called “now” and its value is the time I click a button in my page. Then, when I click that button, within a function I created, the variable “starttime” is subtracted from variable “now” and the result displayed in an alert message (in milliseconds).

Press this button to show how much milliseconds elapsed from a moment document is loaded until now.

Here is the source code:

<!DOCTYPE html>
<html>
	<head>
		<title>Test</title>
	</head>
	<body>
		<script>
			var starttime = Date.now();
			var now;
			function whatsnow(){
				now = Date.now();
				alert("Elapsed in millisec: "+(now-starttime));
			}
		</script>
		<p>Press this button to show how much milliseconds elapsed from a moment document is loaded until now.</p>
		<button onclick="whatsnow()">Show!</button>
	</body>
</html>

What’s next

The next thing we can do is to convert milliseconds into seconds, minuts, hours and so forth. This step is important if we want to calculate, for example, how long ago a user post his/her message, like “3 minutes ago…”, “4 hours and 40 minutes ago…” and so on.

Post Views: 262
ciihuy2020

Welcome!

  • My YouTube Channel
  • My GitHub Page
  • About me

Categories

  • 3DVista
  • Android
  • Apache
  • C#
  • Cordova
  • Electron & Node JS
  • HTML5, CSS & JavaScript
  • iOS
  • Let's Make Unity Games
  • Misc
  • Photoshop
  • PHP
  • Python
  • Uncategorized
  • Unity
  • WordPress

Recent Posts

  • Make objects like wires and cables easily in Unity using Ciihuy Curved Mesh
  • [SOLVED] Can’t Add Custom Domain to Blogger After Losing CNAME Verification
  • iOS App Icon Generator by CiihuyCom
  • Advanced Blinking Marker Script to show objects position in your game canvas
  • Ciihuy Images Merger – Fast & Easy Online Image Combiner
© 2025 ThirteeNov | Powered by Superbs Personal Blog theme