因此,如果您正在尝试编写一个满足您要求的小型 Web 应用程序,那么实际上它并不需要您使用第三方计时器。你真正想要的是Date
对象。然后,您可以使用它来检测当前时间和星期几,并使用它来确定 a) 您想要哪个计时器,以及 b) 计时器结束还有多长时间。
var now = new Date;
var day = now.getDay(); // this returns a number from 0-6, where 0 is Sunday, going through the days of the week.
var month = now.getMonth();
var date = now.getDate();
var year = now.getFullYear();
var target_time; // this will be used to store the time at which the timer elapses
var day_offset; // this stores the number of days we need to offset by until we get to the end of the timer
if(day === 0 || day === 6){
// it's the weekend!
day_offset = (day === 0) ? 1 : 2;
target_time = new Date(year, month, date+day_offset, 0, 0, 0);
} else {
// it's a week day!
day_offset = 6-day; // i think this will work!
target_time = new Date(year, month, date+day_offset, 0, 0, 0);
}
var milliseconds_until_end = target_time.getTime() - Date.now();
// milliseconds_until_end is the number of milliseconds until the timer should end.
// you can parse this in all sorts of ways, but for starters, you could do something
// like this:
var seconds = Math.floor(milliseconds_until_end/1000);
var minutes = seconds/60;
var hours = minutes/60;
var extra_minutes = 60 * (hours - Math.floor(hours));
var extra_seconds = 60 * (extra_minutes - Math.floor(extra_minutes));
hours = Math.floor(hours);
extra_minutes = Math.floor(extra_minutes);
extra_seconds = Math.floor(extra_seconds);
// presumably we want to write all this somewhere!
var output = document.getElementById("output");
output.textContent = hours + ":" + extra_minutes + ":" + extra_seconds;
只是一个警告,我还没有测试过这些。您现在需要做的就是将所有这些代码放在一个 setInterval 中。为此,您首先必须将上述所有代码包装在一个函数定义中(我们可以调用该getTime
函数)。
setInterval(getTime, 1); // this makes the getTime function trigger once every millisecond (not second as i had previously! my bad).