Javascript倒计时器添加7天

问题描述 投票:0回答:4

我尝试在计时器达到 0 时添加 7 天。 你能帮我吗? 它目前达到负值,但我希望它每周二重新启动。

另外,我找到了一些解决方案,但计时器倒计时也在页面刷新时重置,我不希望这样。

            // Countdown timer 
            function makeTimer() {
                var endTime = new Date("October 18, 2020 08:00:00 EST");            
                var endTime = (Date.parse(endTime)) / 1000;

                var now = new Date();
                var now = (Date.parse(now) / 1000);

                var timeLeft = endTime - now;

                var days = Math.floor(timeLeft / 86400); 
                var hours = Math.floor((timeLeft - (days * 86400)) / 3600);
                var minutes = Math.floor((timeLeft - (days * 86400) - (hours * 3600 )) / 60);
                var seconds = Math.floor((timeLeft - (days * 86400) - (hours * 3600) - (minutes * 60)));

                if (hours < "10") { hours = "0" + hours; }
                if (minutes < "10") { minutes = "0" + minutes; }
                if (seconds < "10") { seconds = "0" + seconds; }

                $("#days").html(days + '<span class="camp">Days</span>');
                $("#hours").html(hours + '<span class="camp">Hours</span>');
                $("#minutes").html(minutes + '<span class="camp">Minutes</span>');
                $("#seconds").html(seconds + '<span class="camp">Seconds</span>');       
                }
            setInterval(function() { makeTimer(); 
            }, 1000);
javascript timer countdown
4个回答
0
投票

您必须为浏览器提供一种方法来了解您的结束时间,否则每次都会返回到原始的硬编码值。可以在服务器上存储用户开始和结束计算所需的数据,也可以使用 localStorage 仅在浏览器中执行此操作。

https://developer.mozilla.org/en-US/docs/Web/API/Window/localStorage


0
投票

所以我添加了一个名为

add7Days
的函数,并且检查剩余时间是否小于 0。
每次用完时,这都会为您的变量添加额外的天数。
我还创建了一个对象作为全局变量,因为如果您运行这个对象大概数周,那么如果您每秒重新声明变量,您将开始遇到内存泄漏问题。

var countDownObject = {
    'endDate': new Date('2020-10-19 23:45')
    ,'now': undefined 
    ,'days': 0 
    ,'hours': 0 
    ,'minutes': 0 
    ,'seconds': 0 
    ,'timeLeft': 0 
}; 

function countDown(){ 
    countDownObject.now         = new Date(); 
    countDownObject.timeLeft    = countDownObject.endDate - countDownObject.now; 
    if(timeLeft < 0) add7Days(); /* Function to change time left */
    
    countDownObject.days        = Math.floor(timeLeft / 86400); 
    countDownObject.hours       = Math.floor((timeLeft - (days * 86400)) / 3600); 
    countDownObject.minutes     = Math.floor((timeLeft - (days * 86400) - (hours * 3600 )) / 60); 
    countDownObject.seconds     = Math.floor((timeLeft - (days * 86400) - (hours * 3600) - (minutes * 60))); 
    
    if(hours    < 10) countDownObject.hours     = "0" + hours; 
    if(minutes  < 10) countDownObject.minutes   = "0" + minutes; 
    if(seconds  < 10) countDownObject.seconds   = "0" + seconds; 
    
    $("#days").html(countDownObject.days + '<span class="camp">Days</span>'); 
    $("#hours").html(countDownObject.hours + '<span class="camp">Hours</span>'); 
    $("#minutes").html(countDownObject.minutes + '<span class="camp">Minutes</span>'); 
    $("#seconds").html(countDownObject.seconds + '<span class="camp">Seconds</span>'); 
}; 

function add7Days(){ 
    countDownObject.endDate.setDate(countDownObject.endDate.getDate() + 7); 
    countDownObject.timeLeft = countDownObject.endDate - countDownObject.now; 
}; 
 
setInterval(function(){makeTimer();}, 1000); 

[编辑]

如果您刷新浏览器,您可能希望将对象存储为本地存储

countDownObject

//Set Object localStorage.setItem("countDownObject", JSON.stringify(countDownObject)); //Get Object var countDownObject = JSON.parse(localStorage.getItem("countDownObject"));
或者作为服务器上自己的 json 文件。


0
投票
根据特定时区(周二上午 8 点,在您的情况下是东海岸时间)倒计时到一周中的特定日期和时间的另一种方法是使用第三方时间 API,您可以使用XMLHttpRequest(如果您不需要支持 Internet Explorer,则可以获取)。

第三方时间 API 将为您提供一个包含 GMT 时间的 JSON 对象,以及东部时间的当前偏移量(我在

JSFiddle 示例中使用了纽约)作为标准时间或夏令时,并且还会注明是否是夏令时储蓄是否有效。这可能比取决于访问者的计算机时间更好,访问者的计算机时间可以设置为不同的时区(例如亚利桑那州凤凰城全年使用山区标准时间)。

访问第三方时间 API 可以让您经常重新同步计时器,因此倒计时器不会与实际结束时间相差太远。 setInterval 可能会慢 0.3% 左右,在 6 天的时间内大约需要 30 分钟。

XMLHttpRequest 有一个 onerror 事件处理程序,如果主时间 API 由于某种原因离线,可以使用该事件处理程序连接到备用时间 API。 IE10 和 11 支持 onerror 事件处理程序。

// padStart polyfill for IE if (!String.prototype.padStart) { String.prototype.padStart = function padStart(targetLength, padString) { //floor if number or convert non-number to 0; targetLength = targetLength >> 0; padString = String(typeof padString !== 'undefined' ? padString : ' '); if (this.length > targetLength) { return String(this); } else { targetLength = targetLength - this.length; if (targetLength > padString.length) { //append to original to ensure we are longer than needed padString += padString.repeat(targetLength / padString.length); } return padString.slice(0, targetLength) + String(this); } }; } function countdownTime (endDay, endTimeStr, reachedZero) { var oReq; var endingTimeObj; var currentDateObj; var countdownDisplay = document.getElementById("countdown"); var timeDisplay = document.getElementById("time"); var intervalID = null; var endTime = {}; var numbers = endTimeStr.split(",").map(Number); var cycleCount = 0; endTime.hr = numbers[0]; endTime.min = numbers[1]; endTime.sec = numbers[2]; endTime.ms = numbers[3]; function countdown () { var remainingDays; var remainingHours; var remainingMin; var remainingSec; var delta = endingTimeObj - currentDateObj; if (delta <= 0) { reachedZero(); // call the passed in function endingTimeObj.setUTCDate(endingTimeObj.getUTCDate() + 7); delta = endingTimeObj - currentDateObj; } remainingDays = Math.floor(delta / 86400000); delta = delta - remainingDays * 86400000; remainingHours = Math.floor(delta / 3600000); delta = delta - remainingHours * 3600000; remainingMin = Math.floor(delta / 60000); delta = delta - remainingMin * 60000; remainingSec = Math.floor(delta / 1000); timeDisplay.innerHTML = remainingDays + ":" + remainingHours.toString().padStart(2, "0") + ":" + remainingMin.toString().padStart(2, "0") + "." + remainingSec.toString().padStart(2, "0"); currentDateObj.setSeconds(currentDateObj.getSeconds() + 1); // Sync the countdown after an hour to prevent too much drift cycleCount += 1; if (cycleCount >= 3600) { load(); } } function reqListener () { if(this.readyState === 4 && this.status === 200) { // Stop the existing timer - will create a new timer in a moment if (intervalID !== null) { window.clearInterval(intervalID); intervalID = null; } var obj = JSON.parse(this.responseText); currentDateObj = new Date(obj.datetime); endingTimeObj = new Date(obj.datetime); console.log("GMT: " + currentDateObj.toUTCString()); currentDateObj.setHours(currentDateObj.getHours() + parseInt(obj.utc_offset,10)); console.log("ET: " + currentDateObj.toUTCString()); // Time to the next countdown finish endingTimeObj.setUTCDate(currentDateObj.getUTCDate() + (7 + endDay - currentDateObj.getUTCDay()) % 7); endingTimeObj.setUTCHours(endTime.hr, endTime.min, endTime.sec, endTime.ms); if (currentDateObj > endingTimeObj) { endingTimeObj.setUTCDate(endingTimeObj.getUTCDate() + 7); } console.log("End: " + endingTimeObj.toUTCString()); // display is initially hidden when first loaded countdownDisplay.style.display = "block"; countdown(); intervalID = window.setInterval(countdown, 1000); } } function load() { cycleCount = 0; oReq = new XMLHttpRequest(); oReq.addEventListener("load", reqListener); if (oReq.onerror !== undefined) { // A function to connect to a different time API could go // here (IE9 doesn't support onerror) } oReq.open("GET", "https://worldtimeapi.org/api/timezone/America/New_York"); oReq.send(); } window.onload = load; if ("visibilityState" in document) { document.addEventListener("visibilitychange", function() { if (document.visibilityState === "visible") { load(); } }); } } function reachedZeroAlert () { document.body.style.backgroundColor = "red"; alert("Done"); document.body.style.backgroundColor = "white"; } // Pass in the day (Sunday = 0), // a string for the time of day the countdown should finish, // an the function to execute when the countdown reaches zero countdownTime(2, "08,0,0,0", reachedZeroAlert);
body {
        background-color: white;
    }
    span {
        margin: 0;
        padding: 0;
    }

    #countdown {
        font-family: monospace;
        display: none;
    }

    .values {
        font-size: 2rem;
        margin-left: 0.625rem;
    }

    .labels {
        font-size: 0.8rem;
    }

    .days {
        margin-left: 0.1875rem;
    }

    .hours {
        margin-left: 1.0625rem;
    }

    .minutes {
        margin-left: 1.875rem;
    }

    .seconds {
        margin-left: 1.5625rem;
    }
<div id="countdown">
        <div class="values">
            <span id="time">5:22:43.04</span>
        </div>
        <div class="labels">
            <span class="days">Days</span>
            <span class="hours">Hr</span>
            <span class="minutes">Min</span>
            <span class="seconds">Sec</span>
        </div>
    </div>


0
投票
这效果很好。从您按下“确定”警报的时间起,它会增加 7 天。是否可以通过将 7 天添加到最初设置的时间(在本例中添加到时间 countdownTime(2, "08,0,0,0",reachZeroAlert))的方式来实现?非常感谢

© www.soinside.com 2019 - 2024. All rights reserved.