Search code examples
javascriptjqueryajaxmomentjsmoment-timezone

Auto-refresh time variable (Moments TZ)


I am able to print the current time picked (Input from JSON) using the code below.

However, I need to auto update the variable named j_time every second to show a clock. Please assist.

Note: I've read about setinterval. I am unable to successfully implement the same as the values collected for j_time is also passed to divcontent.

        function onSuccess(data) {
            var objItems = data.d.results;
            var divContent = '<dl class="row" id="infoList">';
            for (var i = 0; i < objItems.length; i++) {
            var j_time = moment.tz(objItems[i].Timezone).format("DD/MM/YYYY HH:mm:ss (Z)");
            console.log(j_time);
                divContent += '<dt class="col-sm-3">Time</dt><dd class="col-sm-9">' + j_time + '</dd>';
            }
            $('#info').append(divContent);
        }

Solution

  • var Timer = (function () {
        function Timer(selector, timeZone) {
            this.time = moment().tz(timeZone);
            this.format = "DD/MM/YYYY HH:mm:ss (Z)";
            this.element = $(selector);
            this.meta = {
                interval: null,
                last: null,
                now: null
            }
            $(selector).data('timer', this);
        }
        Timer.prototype.start = function () {
            var _this = this;
            this.meta.last = this.meta.now = Date.now();
            this.meta.interval = setInterval(function () {
                _this.meta.now = Date.now();
                _this.time.milliseconds(_this.time.milliseconds() + _this.meta.now - _this.meta.last);
                _this.meta.last = _this.meta.now;
                _this.element.text(_this.toString());
            }, 1e3);
        }
        Timer.prototype.stop = function () {
            clearInterval(this.meta.interval);
        }
        Timer.prototype.toString = function () {
            return this.time.format(this.format);
        }
        return Timer;
    }());
    
    var timer = new Timer("#displayTime", "Asia/Kolkata");
    timer.start();
    
    // to stop
    // timer.stop(); // or
    // $("#displayTime").data('timer').stop();
    
    // to get time
    // timer.time; // or
    // $("#displayTime").data('timer').time;
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.29.1/moment.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/moment-timezone/0.5.33/moment-timezone-with-data.min.js" integrity="sha512-rjmacQUGnwQ4OAAt3MoAmWDQIuswESNZwYcKC8nmdCIxAVkRC/Lk2ta2CWGgCZyS+FfBWPgaO01LvgwU/BX50Q==" crossorigin="anonymous"></script>
    
    
    <div id="displayTime"></div>