簡體   English   中英

如何在窗口模糊時暫停計時器並在窗口焦點事件上恢復計時器?

[英]How to Pause the timer on window blur and resume the timer on window focus event?

感謝您看到我的問題。 我正在使用 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;

})();

使用此包裝器功能可以暫停,恢復超時。

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

PS-根據代碼的邏輯使用此功能。 您將必須在代碼中進行相應的計時器調用

我是這樣做的:

 var time0 ; var setTimeout_Int; var focused = true; var resume_Fun ; var addTime =0; var addTimeDiff =0; window.onfocus = function() { focused = true; var d = new Date(); addTimeDiff = addTimeDiff +( d.getTime() - addTime ); resume_Fun(); }; window.onblur = function() { focused = false; }; function init() { var d = new Date(); time0 = d.getTime(); setTimeout_Int = setTimeout(update, 1000 ) } function update() { clearTimeout(setTimeout_Int); var d = new Date(); if(focused) { if(d.getTime() -(time0+addTimeDiff) < 20000) { setTimeout_Int= setTimeout(update, 1000 ) } } else { addTime = d.getTime(); resume_Fun = update; } } init();

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM