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

时间:2017-10-28 07:54:33

标签: javascript php jquery timer

当天的问候,

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

即使页面已刷新或重新加载,我也希望将计时器设置为“继续”。

我打算准备任务管理系统,我想用它。

当我为abc人分配时间时,他/她将启动计时器并停止计时器。

但是当计时器打开时,如果有人刷新页面,则计时器正在停止。

它应该继续。

我尝试了setcookie概念,但在我的情况下它不起作用。

我怎样才能做到这一点。任何帮助将受到高度赞赏。

这是我到目前为止所尝试过的。

  (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)

1 个答案:

答案 0 :(得分:1)

您确定不能正确使用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>