Safari JavaScript setTimeout在最小化时停止

这与以下内容有关:

用于El Capitan的Safari 9.1

Safari 10 for Sierra

当浏览器或标签丢失焦点(主要是最小化)时,有没有人知道Safari在JavaScript引擎中对setTimeout()做了什么?

我创建了一个简单的JavaScript Web应用程序,我在Safari中加载调用JavaScript setTimeout(),该函数传递另一个在超时值后执行的函数.该函数将日期/时间输出到控制台,然后使用相同的超时值调用setTimeout().

如果Safari选项卡失去焦点或浏览器被最小化,经过一段时间后,似乎Safari停止执行setTimeout,并调用后续函数,并且在返回焦点之前,不会执行任何函数.就像事件循环停止处理一样.

注意:没有函数调用丢失,它们只是暂停,并在浏览器重新获得焦点时重新启动.

我在Firefox,Chrome或IE11中没有注意到这一点.

提出这个问题的主要原因是问题主要在我正在维护的Web应用程序中观察到,它使用CometD进行通信回服务器. CometD库使用setTimeout每30秒执行一次返回服务器的请求.如果运行应用程序的浏览器被最小化,似乎CometD停止与服务器通信,直到浏览器再次最大化.

最佳答案 您可能应该使用
setInterval,因为根据
this answer,setInterval仍然有效,即使它被限制为每秒1次.

The setInterval() method of the WindowOrWorkerGlobalScope mixin
repeatedly calls a function or executes a code snippet, with a fixed
time delay between each call. Returns an intervalID.

Syntax var intervalID = scope.setInterval(func, delay[, param1,
param2, …]); var intervalID = scope.setInterval(code, delay);
Parameters

func A function to be executed every delay milliseconds.

code An optional syntax allows you to include a string instead of a function,
which is compiled and executed every delay milliseconds. This syntax
is not recommended for the same reasons that make using eval() a
security risk.

delay The time, in milliseconds (thousandths of a
second), the timer should delay in between executions of the specified
function or code. If this parameter is less than 10, a value of 10 is
used. Note that the actual delay may be longer; see “Reasons for
delays longer than specified” in
WindowOrWorkerGlobalScope.setTimeout() for examples.

param1, …, paramN Optional Additional parameters which are passed through to the
function specified by func once the timer expires.

Timeouts in inactive tabs clamped to >=1000ms

To reduce the load (and associated battery usage) from background
tabs, timeouts are often clamped to firing no more often than once per
second (1000 ms) in inactive tabs.

点赞