用户空闲时启动计时器/用户再次激活后停止并重启计时器

时间:2018-06-17 12:36:01

标签: javascript timer countdown

我有一个计时器功能,在用户空闲5秒后启动。 (所以如果5秒钟什么都不做,倒计时就会开始)

我想要做的就是在用户不再空闲时停止并重置计时器,以便在用户再次空闲时重新启动计时器。

我尝试了#ASSUME NOTHINGclearInterval(),但没有尝试。

我该怎么做?

clearTimeout()
// TIMER
function CountDownTimer(duration, granularity) {
  this.duration = duration;
  this.granularity = granularity || 1000;
  this.tickFtns = [];
  this.running = false;
}

CountDownTimer.prototype.start = function() {
  if (this.running) {
    return;
  }
  this.running = true;
  var start = Date.now(),
      that = this,
      diff, obj;

  (function timer() {
    diff = that.duration - (((Date.now() - start) / 1000) | 0);
    
    if (diff > 0) {
      setTimeout(timer, that.granularity);
    } else {
      diff = 0;
      that.running = false;
    }

    obj = CountDownTimer.parse(diff);
    that.tickFtns.forEach(function(ftn) {
      ftn.call(this, obj.minutes, obj.seconds);
    }, that);
  }());
};

CountDownTimer.prototype.onTick = function(ftn) {
  if (typeof ftn === 'function') {
    this.tickFtns.push(ftn);
  }
  return this;
};

CountDownTimer.prototype.expired = function() {
  return !this.running;
};

CountDownTimer.parse = function(seconds) {
  return {
    'minutes': (seconds / 60) | 0,
    'seconds': (seconds % 60) | 0
  };
};

$(function(){function e(){this.addEventListener("mousemove",n,!1),this.addEventListener("mousedown",n,!1),this.addEventListener("keydown",n,!1),this.addEventListener("DOMMouseScroll",n,!1),this.addEventListener("mousewheel",n,!1),this.addEventListener("touchmove",n,!1),this.addEventListener("MSPointerMove",n,!1),s()}
// IS THE USER INACTIVE?
function s(){d=window.setTimeout(o,5e3)}function n(){window.clearTimeout(d),t()}function o(){  var display = document.querySelector('#time'),
      timer = new CountDownTimer(218);

  timer.onTick(format).onTick(restart).start();

  function restart() {
    if (this.expired()) {
      setTimeout(function() { timer.start(); }, 1000);
    }
  }

  function format(minutes, seconds) {
    minutes = minutes < 10 ? minutes : minutes;
    seconds = seconds < 10 ? seconds : seconds;
    display.textContent = minutes + ':' + seconds;
  }}
// THE USER IS ACTIVE AGAIN
function t(){ 
	 var display = document.querySelector('#time'),
      timer = new CountDownTimer(218);

  timer.onTick(format).onTick(restart).start();

  function restart() {
    if (this.expired()) {
      setTimeout(function() { timer.start(); }, 1000);
    }
  }

  function format(minutes, seconds) {
    minutes = minutes < 10 ? minutes : minutes;
    seconds = seconds < 10 ? seconds : seconds;
    display.textContent = minutes + ':' + seconds;
  }s()}var d;e()});

0 个答案:

没有答案