开发者

Simple JavaScript Timer: substring or datetime?

I have a label with a format ever should be: "00:00:00".

This timer should be开发者_如何学编程 count down via JavaScript, when the timer is 0, there should be a "Ended" in the label.

So how do it with the less performence (e.g.: I have a site with 50 timers, they need to be synchron).

My idea is to split this via substring and -1 them, check if it is -01, then decrement the number before, and set it to 59 again.

Is there an easier way?


I'd go with datetime, and decrement the amount of seconds. Then minutes, hours, days, months, years will be fixed, automatically. Then just have a general formatDate-function that receives a datetime and outputs your "xx:xx:xx" or "ended" depending on it.

Create a new datetime object based on todays date:

var dt = new Date();

Set it to a specific value (note that month is an enum, and starts with 0):

var dt = new Date(2009, 10, 16, 11, 50, 30); // yyyy, mm, dd, hh, mm, ss

Decrease by one second:

dt.setSeconds(dt.getSeconds()-1);

Your converters:

function dateToString(dt) {
   var h = dt.getHours();
   var m = dt.getMinutes();
   var s = dt.getSeconds();

   // ensure there are always at least two characters
   h = ('0' + h).substring(h.toString().length - 2);
   m = ('0' + m).substring(m.toString().length - 2);
   s = ('0' + s).substring(s.toString().length - 2);

   return h + ':' + m + ':' + s;
}

function stringToDate(s) {
   var dateParts = s.split(':');
   var h = parseInt(dateParts[0], 10);
   var m = parseInt(dateParts[1], 10);
   var s = parseInt(dateParts[2], 10);

   return new Date(2009, 0, 1, h, m, s); // if you're only using time, the date doesn't matter
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜