简体   繁体   English

jQuery向后计时器不应在页面刷新时停止(倒数计时器)

[英]JQuery backward timer should not stop on page refresh (Count Down Timer )

Greetings for the day, 当天的问候,

I am using http://oblalex.github.io/jQuery-backward-timer/ . 我正在使用http://oblalex.github.io/jQuery-backward-timer/

I want to set timer as continue even if the page is refreshed or reloaded. 我想将计时器设置为继续,即使刷新或重新加载页面也是如此。

I am going to prepare task management system where i want to use this. 我将准备在其中使用此任务的任务管理系统。

When i allocate time to abc person, he/she will start timer and stop timer. 当我为abc人分配时间时,他/她将启动计时器并停止计时器。

But when the timer is on if person refreshes the page the timer is stoping. 但是当计时器打开时,如果有人刷新页面,计时器将停止。

It should continue. 它应该继续。

I have tried setcookie concept but it's not working in my case. 我已经尝试过setcookie概念,但在我的情况下不起作用。

How can i achieve this. 我怎样才能做到这一点。 Any help will be highly appreciated. 任何帮助将不胜感激。

This is what i have tried so far. 到目前为止,这是我尝试过的。

  (function ($) {
        $(document).ready(function () {
            var allocated_time = $("#allocated_time").val();

            $.backward_timer = function (element) {
                var defaults = {
                    seconds: allocated_time
                    , step: 1
                    , stop_at_zero: false
                    , format: "h%:m%:s%"
                    , value_setter: undefined
                    , on_start: function (timer) {}
                    , on_cancel: function (timer) {}
                    , on_exhausted: function (timer) {}
                    , on_tick: function (timer) {}
                }
                , plugin = this

                plugin.seconds_left = 0
                plugin.target = $(element)
                plugin.timeout = undefined
                plugin.settings = {}

                plugin.methods = {
                    init: function (options) {
                        plugin.settings = $.extend({}, defaults, options)
                        if (plugin.settings.value_setter == undefined) {

                            if (plugin.target.is('input')) {
                                plugin.settings.value_setter = 'val'
                            } else {
                                plugin.settings.value_setter = 'text'
                            }
                        }
                        plugin.methods.reset()
                    }
                    , start: function () {
                        if (
                                plugin.timeout == undefined
                                && !plugin.methods._is_exhausted()
                                ) {
                            plugin.settings.on_start(plugin)

                            var interval = (plugin.seconds_left == plugin.settings.seconds)
                                    ? 0
                                    : plugin.settings.step * 1000
                            setTimeout(plugin.methods._on_tick, interval, interval)
                        }
                    }
                    , cancel: function () {
                        if (plugin.timeout != undefined) {
                            clearTimeout(plugin.timeout)
                            plugin.timeout = undefined
                            plugin.settings.on_cancel(plugin)
                        }
                    }
                    , reset: function () {
                        plugin.seconds_left = plugin.settings.seconds
                        plugin.methods._render_seconds()
                    }
                    , _on_tick: function (previous_delay) {
                        if (previous_delay != 0) {
                            plugin.settings.on_tick(plugin)
                        }

                        plugin.methods._render_seconds()

                        if (plugin.methods._is_exhausted()) {
                            plugin.timeout = undefined
                            plugin.settings.on_exhausted(plugin)
                        } else {
                            if (
                                    plugin.seconds_left < plugin.settings.step
                                    && plugin.settings.stop_at_zero
                                    ) {
                                var step = plugin.seconds_left
                            } else {
                                var step = plugin.settings.step
                            }
                            plugin.seconds_left -= step
                            var interval = step * 1000
                            plugin.timeout = setTimeout(plugin.methods._on_tick,
                                    interval,
                                    interval)
                        }
                    }
                    , _render_seconds: function () {
                        var dhms = plugin.methods._seconds_to_dhms(plugin.seconds_left)
                                , value = plugin.settings.format

                        if (value.indexOf("d%") !== -1) {
                            value = value
                                    .replace('d%', dhms.d)
                                    .replace('h%', plugin.methods._check_leading_zero(dhms.h))
                        } else {
                            value = value.replace('h%', dhms.d * 24 + dhms.h)
                        }

                        value = value
                                .replace('m%', plugin.methods._check_leading_zero(dhms.m))
                                .replace('s%', plugin.methods._check_leading_zero(dhms.s))

                        if (plugin.seconds_left < 0) {
                            value = '-' + value
                        }

                        plugin.target[plugin.settings.value_setter](value)
                    }
                    , _seconds_to_dhms: function (seconds) {
                        var seconds = Math.abs(seconds)
                                , days = Math.floor(seconds / (24 * 3600))
                                , seconds = seconds - (days * 24 * 3600)
                                , hours = Math.floor(seconds / 3600)
                                , seconds = seconds - (hours * 3600)
                                , mins = Math.floor(seconds / 60)
                                , seconds = Math.floor(seconds - (mins * 60))

                        window.onload = function () {
                            setCookie("minutes", mins.toString(), 1);
                            setCookie("seconds", seconds.toString(), 1);
                            setCookie("hours", hours.toString(), 1);
                            setCookie("days", days.toString(), 1);
                            mins = getCookie("minutes");
                            seconds = getCookie("seconds");
                            hours = getCookie("hours");
                            days = getCookie("days");
                        };

                        return {d: days, h: hours, m: mins, s: seconds}
                    }
                    , _check_leading_zero: function (number) {
                        return (number < 10)
                                ? '0' + number
                                : '' + number
                    }
                    , _is_exhausted: function () {
                        return plugin.seconds_left <= 0 && plugin.settings.stop_at_zero
                    }
                }
            }

            $.fn.backward_timer = function (method_or_options) {
                var options = arguments

                return this.each(function () {
                    var plugin = $(this).data('backward_timer')

                    if (plugin == undefined) {
                        plugin = new $.backward_timer(this)
                        $(this).data('backward_timer', plugin);
                    }

                    if (plugin.methods[method_or_options]) {
                        return plugin.methods[method_or_options]
                                .apply(this, Array.prototype.slice.call(options, 1))
                    } else if (
                            typeof method_or_options === 'object'
                            || !method_or_options
                            ) {
                        return plugin.methods.init.apply(this, options)
                    } else {
                        $.error(
                                'Method '
                                + method_or_options
                                + ' does not exist on jQuery.backward_timer'
                                )
                    }
                })
            }

        });

    })(jQuery)

Are you sure that you can't use cookie properly ? 您确定不能正确使用Cookie吗? And why ? 又为什么呢?

I propose to do it differently, with a timestamp in the cookie: 我建议采用不同的方式,在cookie中添加时间戳:

<div>    
    <span id="timer_default" class="timer"></span>
    <button id="reset_default">Reset</button>
</div>

<script>
$(document).ready(function(){
  var timerEl = $('#timer_default');
  var timeCount = 3600; // one hour
  var timeLeft = timeCount - (+new Date() - createOrGetCookieTime()); // compare timestamp with now

  $('#timer_default').backward_timer({
      seconds: timeLeft ,
      format: 'd%d h%:m%:s%',
      on_exhausted: function(timer) {
         timer.target.text('I am exhausted. Reset me!')
      }
  });

  // start directly
  timerEl.backward_timer('start');

  // if timer is ended (in case of exhausted didn't handle it, not sure)
  if(timeLeft < 0){ 
    timerEl.backward_timer('cancel');
    timerEl.text('I am exhausted. Reset me!')
  }

  $('#reset_default').click(function() {
    timerEl.backward_timer('reset');
    setCookie("time", +new Date(), 1); // add timestamp in cookie again
  });

});

// create or get the cookie
function createOrGetCookieTime() {

  var timeCookie=RegExp(""+time+"[^;]+").exec(document.cookie);
  if(!!timeCookie){
      return +decodeURIComponent(timeCookie.toString().replace(/^[^=]+./,"")); // get last timestamp
  }else{
      setCookie("time", +new Date(), 1); // add timestamp in cookie
      return 0;
  }
}


</script>

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

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