icbxw
icbxw

Reputation: 59

How to calculate the milliseconds in Javascript CountUp Timer?

I found a script that is able to CountUp from a preset date but would like to add miliseconds to it.

What I have right now:

var minutes = Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60));
var seconds = Math.floor((distance % (1000 * 60)) / 1000);

I can see that milliseconds should look something like this

var milliseconds = Math.floor((distance % (****)) / **** );

How is it calculated I wonder ?

Edit: I might be not so explicit so here is more of the code ?

The function:

var x = setInterval(function(){ ......... }, 1000);

Inside the function lies this:

var now = new Date().getTime();

    var distance = now - dateCountup;

   ..............



 var minutes = Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60));
    var seconds = Math.floor((distance % (1000 * 60)) / 1000);

document.getElementById(".....").innerHTML = ......... + minutes + "m " + seconds + "s ";

is distance the milliseconds ?

Upvotes: 2

Views: 1322

Answers (1)

Anurag Srivastava
Anurag Srivastava

Reputation: 14423

You can easily get that using Date.getTime(). Use it inside your setInterval / setTimeout:

var since = new Date("01-01-2020");
var now = new Date();
console.log(now.getTime() - since.getTime() + " ms")

// Assuming you count every 1/100th of a second
setInterval(() => {
  now = new Date();
  console.clear()
  console.log(now.getTime() - since.getTime() + " ms")
}, 10)

Upvotes: 2

Related Questions