交替重复倒计时 - html - javascript

Alternating Repeating Countdown - html - javascript

显然这个问题有多个部分:一个是倒计时,另一个是交替显示哪个部分。我想要周末倒计时(星期六00:00),在周末它会显示周末结束倒计时(星期一00:00)

所以首先是倒计时:我能看到的方式是进入倒计时网站,然后使用它就会在那里,唯一的问题是这不适合背景,你必须滚动。所以你必须使用其他方法。

其次是交替:我对此没有太多想法,但我必须考虑一些事情,否则这是题外话。所以如果我想让它改变两次。我可以将倒计时设置为一个变量 (x),然后您将测试 x 是否为 0,然后将 1 加到 y,当它是奇数时,显示 5 天倒计时(432000 秒),然后当它是偶数时显示2 天倒计时(172800 秒)所以这是我的(可能失败的)尝试:

    if x=0 {
        if y=1 {
           var z=432000
        }
        else {
           var z=172000
        }
    }

我不知道这是否正确,但我希望你能欣赏我的尝试。提前致谢!

因此,如果您正在尝试编写一个小型 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).