如何在窗口模糊时暂停计时器并在窗口焦点事件上恢复计时器?

时间:2016-02-25 08:26:50

标签: javascript php jquery wordpress-plugin

感谢您看到我的问题。 我正在使用wp-pro-quiz插件进行测验。我想知道如果窗口没有对焦或模糊,我怎么能暂停计时器,并在它回到焦点时恢复它。 我的代码: 当它集中注意力时我会重置

var timelimit = (function () {
var _counter = config.timelimit;
var _intervalId = 0;
var instance = {};

instance.stop = function () {
    if (_counter) {
        window.clearInterval(_intervalId);
        globalElements.timelimit.hide();
    }
};

instance.start = function () {
    var x;
    var beforeTime;
    if (!_counter)
        return;
    var $timeText = globalElements.timelimit.find('span').text(plugin.methode.parseTime(_counter));
    var $timeDiv = globalElements.timelimit.find('.wpProQuiz_progress');

    globalElements.timelimit.show();
    $.winFocus(function (event) {
        console.log("Blur\t\t", event);
    },
    function (event) {
        console.log("Focus\t\t", event);
        x = _counter * 1000;
        beforeTime = +new Date();
    });

    _intervalId = window.setInterval(function () {

        var diff = (+new Date() - beforeTime);
        var elapsedTime = x - diff;

        if (diff >= 500) {
            $timeText.text(plugin.methode.parseTime(Math.ceil(elapsedTime / 1000)));
        }

        $timeDiv.css('width', (elapsedTime / x * 100) + '%');

        if (elapsedTime <= 0) {
            instance.stop();
            plugin.methode.finishQuiz(true);
        }

    }, 16);
};

return instance;

})();

1 个答案:

答案 0 :(得分:0)

使用此包装函数暂停,恢复超时。

var Timer;

Timer = function(callback, delay) {
  var remaining, start, timerId;
  timerId = void 0;
  start = void 0;
  remaining = delay;
  this.pause = function() {
    window.clearTimeout(timerId);
    remaining -= new Date - start;
  };
  this.resume = function() {
    start = new Date;
    window.clearTimeout(timerId);
    timerId = window.setTimeout(callback, remaining);
  };
  this.resume();
};

像这样初始化它,timer = new Timer("callback_function_here", 45000) 在这种情况下,回调和事件触发的总时间为45秒(在您的情况下为模糊或焦点),它将相应地暂停或恢复计时器。

timer.pause() //pause the timer
timer.resume() //resume the timer

P.S - 根据代码的逻辑使用此功能。您必须在代码中相应地进行计时器调用