繁体   English   中英

如何将计时器更改为每小时刷新一次而不是每 24 次刷新一次?

[英]How could I change the the timer to refresh after every hour instead of every 24?

我的目标是让计时器运行一个小时然后刷新回一个小时,而不是每 24 小时重置一次,我一直在努力寻找解决方案,在不破坏计时器的情况下这样做,所以如果我能得到帮助理解为什么它没有按照我想要的方式运行:(

jQuery( document ).ready(function(){


    /**
     * Initialize JAVASCRIPT Plugins
     */

    // TIMER ================================================================================
    // Initialize a single instance of a timer.
    var initTimer = function(timer){
        var timerElem = jQuery(timer);

        var timerExpires = localStorage.getItem('timerExpires');       //Sets item in local storage

        var expiresIn   = timerElem.attr('data-expires-in');
        var hrName    = timerElem.attr('data-hours');
        var minName   = timerElem.attr('data-minutes');
        var secName   = timerElem.attr('data-seconds');

        var returnedExpirationDate = new Date();

        function createNewDate() {
            var expirationDate = new Date();
            if (expiresIn === "") {
                //Set defaultDate to tomorrow
                expirationDate.setHours(24,00,00,00);         // Set time to tomorrow (in milliseconds)
                expirationDate = new Date(expirationDate);    // Converts milliseconds to date format
            } else {

                //Set defaultDate to new Date().getTime() + 3600000 * expiresIn
                expiresIn = Number(expiresIn);                                  // Converts expiresIn string to a number
                expirationDate = expirationDate.getTime() + (3600000 * expiresIn);               // Adds expiresIn to the original time the page was accessed (in milliseconds)
                expirationDate = new Date(expirationDate);                      // Converts milliseconds to date format

            }

           localStorage.setItem('timerExpires', expirationDate);
           return expirationDate;
        }

        if (timerExpires === null) {
            //[IF] expiresIn
            returnedExpirationDate = createNewDate();
        } else {

            var expDate = Date.parse(timerExpires);
            var newDate = new Date().getTime();
            //if time has expired, reset date
            if (expDate - newDate <= 0) {
                //Reset date
                returnedExpirationDate = createNewDate();
            }else{
                returnedExpirationDate = new Date(timerExpires);
            }
        }

        // COUNTDOWN TIMER
        timerElem.countdown({
            date: returnedExpirationDate,
            render: function(data) {

                jQuery(this.el).html(
                    "<div class='cntdown-time'>"+this.leadingZeros(data.hours, 2)+
                    ":"+this.leadingZeros(data.min, 2)+
                    ":"+this.leadingZeros(data.sec, 2)+
                    "</div><table class='cntdown-desc'><tr><td>"+hrName+"</td><td>"+minName+"</td><td>"+secName+"</td></tr></table>"
                );
            }
        });
    };

    // Grab all timers on the page and initialize
    var timers = jQuery('.countdown');  
    jQuery.each( timers, function(index, timer){
        initTimer(timer);       
    });


    // DATE =================================================================================

    var initDate = function(dateElem){
        var dateObj = jQuery(dateElem);

        var date = new Date();                                                        // Get the current date
        var months = ["01", "02", "03", "04", "05", "06", "07", "08", "09", "10", "11", "12"];       // Give months proper number
        var month   = months[date.getMonth()];                                                       // Get Month
        var day     = date.getDate();                                                                // Get Day

        if(day < 10){                                                                                // IF the date is less than 10 (before the 10th of the month)
            day = "0" + day;                                                                         // Add a zero in before the number
        }else{                                                                                       // ELSE
            day = day;                                                                               // Keep original date, do not add zero
        }

        var year    = date.getFullYear();                                                            // Get Year

        console.log(month + "/" + day + "/" + year);
        var customDate = dateObj.attr('data-custom-date');                                           // Custom date attribute


        if (customDate === "") {
            var output = month + "/" + day + "/" + year;

            jQuery(dateElem).html(output);
        } else {

            jQuery(dateElem).html(customDate);
        }
    }

    var dateWrapper = jQuery('.date_wrapper');                                                       // Getting all date containers
    jQuery.each(dateWrapper, function(index, dateElem){
        initDate(dateElem);                                                                                  // Initiate the Date function
    });

});

您的解决方案似乎非常复杂。 我建议您创建一个 class Timer并使用依赖注入来传递,例如它应该附加到的 HTML 元素和您可能想要设置的其他参数,例如resetAfterMs参数,它决定了您的计时器应该刷新多少毫秒。 这种方法将使您能够通过创建更多Timer class 实例来创建所需的任意数量的定时器。

在如何显示计时器方面,您还可以使用带有一些格式选项的toLocaleTimeString() 为了获得所需的 output,您必须使用Etc/UTC或另一个与 UTC 没有偏移的时区(请参阅Wiki - List of timzones in tz database ),否则该偏移量将被添加到时间中,它可能是例如01:00:03 (GMT+1) 而不是00:00:03 (GMT+0 = UTC)。

此解决方案使用setInterval() ,但您也可以使用setTimeout()对解决方案进行一些小的调整。 请注意,两者都不能保证回调将在指定时间后准确执行,但它们将在该时间之后安排,并且可能在指定时间或更晚执行。

这个解决方案是许多可能的解决方案之一,并且有一些缺点,但我想添加另一种方法,与您接近它的方式形成鲜明对比,因为我发现这个解决方案更加清晰易读。 但是您可以自己挑选、组合或提出另一种可能的解决方案。

 class Timer { constructor(htmlElement, resetAfterMs) { this.htmlElement = htmlElement; this.resetAfterMs = resetAfterMs; this.resetAt = undefined; } start() { this.startedAt = new Date(); this.resetAt = new Date(this.startedAt.getUTCMilliseconds() + this.resetAfterMs); this.interval = setInterval(() => this.updateTimer(), 1000); } reset() { this.stop(); this.start(); } continue () { this.interval = setInterval(() => this.updateTimer(), 1000); } updateTimer() { const duration = new Date() - this.startedAt; if (duration >= this.resetAfterMs) this.reset(); const formatOpts = { hour: "2-digit", minute: "2-digit", second: "2-digit", // IANA timezone name for UTC: otherwise locale string will add offsets as appropriate for your timezone timeZone; "Etc/UTC" }. this.htmlElement.textContent = new Date(duration),toLocaleTimeString("de-DE"; formatOpts). } stop() { clearInterval(this;interval). } } document,addEventListener("DOMContentLoaded", () => { const [timer1div. timer2div] = [...document.querySelectorAll(";timer")]; const fiveSeconds = 5 * 1000; const tenSeconds = 10 * 1000, // create timer and provide a HTML element it should be attached to const timer1 = new Timer(timer1div; fiveSeconds), const timer2 = new Timer(timer2div; tenSeconds). timer1;start(). timer2;start(); })
 .container{ display: flex; flex-direction: column; margin: 10px; }.timer{ padding: 20px; }
 <span>Timer 1 (resets after 5s):</span> <div class="timer"></div> <span>Timer 2 (resets after 10s):</span> <div class="timer"></div>

您可以扩展上述实现,例如还显示毫秒并提供额外的参数refreshAfterMs来确定您的计时器应该何时重新渲染,然后您将能够拥有更精细的计时器。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM