我有一个setInterval,每秒运行一段代码30次。这工作得很好,但是当我选择另一个选项卡(使我的代码选项卡变得不活跃),setInterval由于某种原因被设置为空闲状态。

我制作了这个简化的测试用例(http://jsfiddle.net/7f6DX/3/):

var $div = $('div');
var a = 0;

setInterval(function() {
    a++;
    $div.css("left", a)
}, 1000 / 30);

如果您运行这段代码,然后切换到另一个选项卡,等待几秒钟并返回,动画将继续在切换到另一个选项卡时的位置。

因此,如果标签处于非活动状态,动画不会每秒运行30次。这可以通过计算每秒调用setInterval函数的次数来确认——如果选项卡处于非活动状态,这将不是30,而是1或2。

我想这样做是为了提高系统性能,但是有什么方法可以禁用这种行为吗?

这在我看来是劣势。


当前回答

我修改了Lacerda的回应,添加了一个功能正常的UI。

我添加了启动/恢复/暂停/停止操作。

const timer = document.querySelector('.timer'), timerDisplay = timer.querySelector('.timer-display'), toggleAction = timer.querySelector('[data-action="toggle"]'), stopAction = timer.querySelector('[data-action="stop"]'), tickRate = 10; let intervalId, initialTime, pauseTime = 0; const now = () => new Date().getTime(); const formatTime = (hours, minutes, seconds) => [hours, minutes, seconds] .map(v => `${isNaN(v) ? 0 : v}`.padStart(2, '0')) .join(':'); const update = () => { let time = (now() - initialTime) + 10, hours = Math.floor((time / (60000)) % 60), minutes = Math.floor((time / 1000) % 60), seconds = Math.floor((time / 10) % 100); timerDisplay.textContent = formatTime(hours, minutes, seconds); }; const startTimer = () => { initialTime = now(); intervalId = setInterval(update, tickRate); }, resumeTimer = () => { initialTime = now() - (pauseTime - initialTime); intervalId = setInterval(update, tickRate); }, pauseTimer = () => { clearInterval(intervalId); intervalId = null; pauseTime = now(); }, stopTimer = () => { clearInterval(intervalId); intervalId = null; initialTime = undefined; pauseTime = 0; }, restartTimer = () => { stopTimer(); startTimer(); }; const setButtonState = (button, state, text) => { button.dataset.state = state; button.textContent = text; }; const handleToggle = (e) => { switch (e.target.dataset.state) { case 'pause': setButtonState(e.target, 'resume', 'Resume'); pauseTimer(); break; case 'resume': setButtonState(e.target, 'pause', 'Pause'); resumeTimer(); break; default: setButtonState(e.target, 'pause', 'Pause'); restartTimer(); } }, handleStop = (e) => { stopTimer(); update(); setButtonState(toggleAction, 'initial', 'Start'); }; toggleAction.addEventListener('click', handleToggle); stopAction.addEventListener('click', handleStop); update(); html, body { width: 100%; height: 100%; margin: 0; padding: 0; } body { display: flex; justify-content: center; align-items: center; background: #000; } .timer { display: flex; flex-direction: column; justify-content: center; align-items: center; gap: 0.5em; } .timer .timer-display { font-family: monospace; font-size: 3em; background: #111; color: #8F8; border: thin solid #222; padding: 0.25em; } .timer .timer-actions { display: flex; justify-content: center; gap: 0.5em; } .timer .timer-actions button[data-action] { font-family: monospace; width: 6em; border: thin solid #444; background: #222; color: #EEE; padding: 0.5em; cursor: pointer; text-transform: uppercase; } .timer .timer-actions button[data-action]:hover { background: #444; border: thin solid #666; color: #FFF; } <div class="timer"> <div class="timer-display"></div> <div class="timer-actions"> <button data-action="toggle" data-state="initial">Start</button> <button data-action="stop">Stop</button> </div> </div>

其他回答

我认为最好的理解这个问题的例子是:http://jsfiddle.net/TAHDb/

我在这里做了一件简单的事情:

间隔1秒,每次隐藏第一个跨度,并将其移动到最后,并显示第二个跨度。

如果你停留在页面上,它就像它所设想的那样工作。 但如果你把标签隐藏了几秒钟,当你回来的时候,你会看到一个奇怪的东西。

这就像所有在你现在不活跃的时候没有发生的事情都会在一次发生一样。所以在几秒钟内你会看到X个事件。它们是如此之快,以至于有可能同时看到所有6个跨度。

所以它接缝铬只延迟事件,所以当你回来所有的事件将发生,但所有的一次…

这是一个简单的幻灯片的实际应用。想象数字是图像,如果用户保持标签隐藏,当他回来的时候,他会看到所有的imgs浮动,完全混乱。

要解决这个问题,请像pimvdb告诉的那样使用stop(true,true)。 这将清除事件队列。

注意:这个解决方案不适合如果你喜欢你的间隔工作在背景上,例如,播放音频或其他东西。但如果你感到困惑,例如当你回到页面或选项卡时,你的动画不能正常工作,这是一个很好的解决方案。

有很多方法可以实现这个目标,也许“WebWorkers”是最标准的一个,但当然,它不是最简单和方便的一个,特别是如果你没有足够的时间,所以你可以试试这种方法:

基本概念:

为你的间隔(或动画)建立一个名字,并设置你的间隔(动画),所以它会运行时,用户第一次打开你的页面:var interval_id = setInterval(your_func, 3000); 通过$(window).focus(function() {});$(window).blur(function() {});你可以clearInterval(interval_id)每次浏览器(标签)是去激活和重新运行你的间隔(动画)每次浏览器(标签)将再次激活interval_id = setInterval();

示例代码:

var interval_id = setInterval(your_func, 3000);

$(window).focus(function() {
    interval_id = setInterval(your_func, 3000);
});
$(window).blur(function() {
    clearInterval(interval_id);
    interval_id = 0;
});

我为那些试图在计时器函数中解决这个问题的人带来了一个简单的解决方案,正如@kbtzr在另一个答案中提到的那样,我们可以使用Date对象而不是固定增量来计算自开始以来经过的时间,即使您离开了应用程序的选项卡,这也可以工作。

这是HTML示例。

<body>
  <p id="time"></p>
</body>

然后这个JavaScript:

let display = document.querySelector('#time')
let interval
let time
function startTimer() {
    let initialTime = new Date().getTime()
    interval = setInterval(() => {
        let now = new Date().getTime()
        time = (now - initialTime) + 10
        display.innerText = `${Math.floor((time / (60 * 1000)) % 60)}:${Math.floor((time / 1000) % 60)}:${Math.floor((time / 10) % 100)}`
    }, 10)
}
startTimer()

这样,即使由于非活动选项卡的性能原因而增加了间隔值,所做的计算也将保证正确的时间。这是一个普通的代码,但我在我的React应用程序中使用了这种逻辑,你也可以在任何你需要的地方修改它。

只要这样做:

var $div = $('div');
var a = 0;

setInterval(function() {
    a++;
    $div.stop(true,true).css("left", a);
}, 1000 / 30);

不活跃的浏览器选项卡缓冲了一些setInterval或setTimeout函数。

Stop (true,true)将停止所有缓冲事件,并立即只执行最后一个动画。

window.setTimeout()方法现在限制在非活动选项卡中每秒发送不超过一个超时。此外,它现在将嵌套超时限制到HTML5规范允许的最小值:4毫秒(而不是以前的10毫秒)。

这是我的粗略解决方案

(function(){
var index = 1;
var intervals = {},
    timeouts = {};

function postMessageHandler(e) {
    window.postMessage('', "*");

    var now = new Date().getTime();

    sysFunc._each.call(timeouts, function(ind, obj) {
        var targetTime = obj[1];

        if (now >= targetTime) {
            obj[0]();
            delete timeouts[ind];
        }
    });
    sysFunc._each.call(intervals, function(ind, obj) {
        var startTime = obj[1];
        var func = obj[0];
        var ms = obj[2];

        if (now >= startTime + ms) {
            func();
            obj[1] = new Date().getTime();
        }
    });
}
window.addEventListener("message", postMessageHandler, true);
window.postMessage('', "*");

function _setTimeout(func, ms) {
    timeouts[index] = [func, new Date().getTime() + ms];
    return index++;
}

function _setInterval(func, ms) {
    intervals[index] = [func, new Date().getTime(), ms];
    return index++;
}

function _clearInterval(ind) {
    if (intervals[ind]) {
        delete intervals[ind]
    }
}
function _clearTimeout(ind) {
    if (timeouts[ind]) {
        delete timeouts[ind]
    }
}

var intervalIndex = _setInterval(function() {
    console.log('every 100ms');
}, 100);
_setTimeout(function() {
    console.log('run after 200ms');
}, 200);
_setTimeout(function() {
    console.log('closing the one that\'s 100ms');
    _clearInterval(intervalIndex)
}, 2000);

window._setTimeout = _setTimeout;
window._setInterval = _setInterval;
window._clearTimeout = _clearTimeout;
window._clearInterval = _clearInterval;
})();