steve k steve k - 3 months ago 9
Javascript Question

Removing string property on time with/without moment.js

I am creating a countdown on a session that is 20 minutes. When I do a get request I get back

20.


This is fine. My next step is to set this so that it can be subtracted by

1000 milliseconds on an $interval


I have tried the following code

var d = moment.duration(x, 'milliseconds');
moment(d.asMinutes(),'mm').format('mm:ss');


Which returns

"21:00"


This is great, but the problem is now I have a string. I am not sure how I can start subtracting seconds off of this timer.

Any help would be greatly appreciated.

Answer

If you just want a session timeout there's no need to complicate things, use setTimeout:

const SESSION_MAX = 20 * 60 * 1000; // 20 min to milliseconds
setTimeout(logOutFunction, SESSION_MAX);

If for some reason you want more control, then just work with the integers returned by a Date object's native getTime:

let start = Date.now();
let end = start + (20 * 60 * 1000);
const INTERVAL = 1000; //ms

Then increment start on a clocktick and check if its >= end.