SBB
SBB

Reputation: 8990

Javascript date + milliseconds

I am working on a pause function for a timer I have built and I am getting a little stuck.

As soon as the timer starts, I capture the current date in milliseconds:

if(!begin){
   begin = Date.now();
}

Once the user has clicked pause, it will then get the current date in milliseconds.

// Pause the timer
function pause(){
   console.log('Begin : ' + begin) //Begin : 1467580324524
   console.log('End: ' + currentDate().getTime()) //End: 1467580329936
   console.log('Difference: ' + parseInt(begin - currentDate().getTime())) //Difference: -5414
   clearInterval(interval);
}

I now have a variable called difference that contains the number of milliseconds between the start time and stop time.

When the user clicks "Resume", I need to get the current date and add the difference of milliseconds we got. That should then resume the timer from where they currently left off using the new point in time.

How can I go about adding the milliseconds to the current date in order to get the new starting point?

I tried something like this with no luck:

var mili = 4512;
var newDate = new Date(mili*1000);

UPDATE: here is a link to my timer code so you can see what I am working with. https://jsfiddle.net/3dweffy8/3/

I got the timer to pause by clearing the interval but I am not sure how to continue with getting the timer to resume at this point.

Upvotes: 0

Views: 113

Answers (2)

Michał Perłakowski
Michał Perłakowski

Reputation: 92709

Get the current timestamp using Date.now(), add the amount of milliseconds and make a new Date object from it:

var newDate = new Date(Date.now() + mili)

Upvotes: 1

thst
thst

Reputation: 4602

Write an Object to do the bookkeeping.

The object will carry the last timestamp and the measurements, either as a sum or as an array.

It exposes function start(), stop(), pause(), resume().

in start(): reset the measurements and get the current Date as referenceDate for your next measurement. If the tracker is already running, do nothing.

stop(): calculate the difference between current date and referenceDate. The counter is no longer active. Maybe archive the remaining results.

pause(): calculate the difference between current date and referenceDate. If you want to measure breaks, set referenceDate to current date.

resume(): If you measure breaks, calculate the difference between current date and referenceDate. In any case, set referenceDate to current date.

Usage:

var tracker = new Tracker();

// start 
tracker.start(); 

// Pause the timer
function pause(){
   tracker.pause();

   console.log('Begin : ' + tracker.startOfEvents); //Begin:1467580324524
   console.log('End: ' + tracker.lastMeasurement); //End: 1467580329936
   console.log('Difference: ' + tracker.difference) //Difference: -5414

   // was this part of your measurement?
   clearInterval(interval);
}

// later
tracker.resume();

Upvotes: 0

Related Questions