Making a min:sec counter using javascript -


i trying make small question/answer quiz game using react, , want show timer counts down every second. each game last 10, 15, or 30 minutes @ most, want show timer updates every second in bottom of screen (in big font, of course!), 15:00, 14:59, 14:58, , on until hits 00:00.

so, given start time such 2016-04-25t08:00:00z, , end time after adding 15 min of 2016-04-25t08:15:00z, want start countdown.

my issue not understanding how use setintervals keep calling method find remaining time.

timeleft = math.round(timeleft/1000) * 1000; const timer = new date(timeleft); return timer.getutcminutes() + ':' + timer.getutcseconds(); 

edit: you've edited question. need time padding, , method below faster using, answer question setinterval:

first, define function run timer , decrement each time it's called:

var timeleft; // time left var elem; // dom element timer text goes var interval = null; // interval pointer stored in variable  function tick() {   timeleft = math.round(timeleft / 1000) * 1000;   const timer = new date(timeleft);   var time = timer.getutcminutes() + ':' + timer.getutcseconds();   elem.innerhtml = time;    timeleft -= 1000; // decrement 1 second    if (timeleft < 0) {     clearinterval(interval);   } }  interval = setinterval(tick, 1000); 

og answer:

no, not believe there built-in way display time differences.

let's have 2 date objects:

var start = date.now(); var end = date.now() + 15 * 60 * 1000; // 15 minutes 

then can subtract 2 date objects number of milliseconds between them:

var diff = (end - start) / 1000; // difference in seconds 

to number of minutes, take diff , divide 60 , floor result:

var minutes = math.floor(diff / 60); 

to number of seconds, take modulus remainder after minutes removed:

var seconds = diff % 60; 

but want these 2 padded zeros, that, convert strings , check if 2 characters long. if not, prepend zero:

// assumes num whole number function pad2digits(num) {   var str = num.tostring();   if (str.length === 1) {     str = '0' + str;   }   return str; }  var time = pad2digits(minutes) + ':' + pad2digits(seconds); 

now have time in minutes , seconds.


Comments

Popular posts from this blog

javascript - How to get current YouTube IDs via iMacros? -

c# - Maintaining a program folder in program files out of date? -

emulation - Android map show my location didn't work -