Counting how much time elapsed using JavaScript

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:

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.

Published by


Habibie is an Indonesian freelance frontend-backend web developer and cross platform mobile app programmer. He's also good at graphics design, video editing, visual effects and animation.