Building a Real-Time Countdown

Hello!

I’m trying to build a real-time countdown clock in my Cocos Creator-based app.

It is supposed to not pause when users leave the app (e.g. on iOS or Android) - rather, after resuming the app, the time that has passed in the meantime should be subtracted from the countdown. (That is: no ‘cheating’ the countdown by leaving the app.)

What would a ‘update()’ function look like for this?

Any advice (accessing the device’s clock, or so) is welcome.

JS stores the current date and time as a long numerical value:

17:57:23.518 Date.now()
17:57:23.527 1516413443520

so you can figure out what you ‘start time’ is and use that number

let’s assume your start time was the time above 17:57:23:518
then you save ‘1516513443520’ and use it to init your ‘start time’ var

18:01:03.718 var startTime = new Date(1516413443520)
18:01:06.036 startTime
18:01:06.047 Fri Jan 19 2018 17:57:23 GMT-0800 (PST)

now you can get your duration by subtraction

17:57:23 GMT-0800 (PST)
18:02:04.926 Date.now()
18:02:04.933 1516413724928
18:02:33.760 var duration = 1516413724928 - 1516413443520
18:02:33.768 281408

now comes the tricky part, you have to convert your duration into days, hours, minutes, and seconds by using time base math: for example a day is (24 * 60 * 60 * 1000) milliseconds long, so then you divide your duration by millisecondsPerDay,

then for each subsequent unit of measure, in this case it would be hours after days, you need to subtract away how many days you just tallied and then do the same math on the new duration but for hours

var	millisecondsPerDay = 24 * 60 * 60 * 1000;
var	millisecondsPerHour = 60 * 60 * 1000;
var	millisecondsPerMinute = 60 * 1000;
var	days = Math.floor(duration / millisecondsPerDay);
var	hours = Math.floor((duration - days * millisecondsPerDay) / millisecondsPerHour);
var	minutes = Math.floor((duration - days * millisecondsPerDay - hours * millisecondsPerHour) / millisecondsPerMinute);
var	seconds = Math.floor((duration - days * millisecondsPerDay - hours * millisecondsPerHour - minutes * millisecondsPerMinute) / 1000);
1 Like