From af3288b106f44aaaa2c80d499ec669383d6f7203 Mon Sep 17 00:00:00 2001 From: MDN Date: Wed, 1 Sep 2021 00:52:00 +0000 Subject: [CRON] sync translated content --- files/zh-cn/web/api/atob/index.html | 75 +++ files/zh-cn/web/api/btoa/index.html | 172 ++++++ files/zh-cn/web/api/caches/index.html | 128 +++++ files/zh-cn/web/api/clearinterval/index.html | 75 +++ files/zh-cn/web/api/cleartimeout/index.html | 151 +++++ files/zh-cn/web/api/createimagebitmap/index.html | 208 +++++++ files/zh-cn/web/api/crossoriginisolated/index.html | 59 ++ files/zh-cn/web/api/fetch/index.html | 174 ++++++ files/zh-cn/web/api/indexeddb/index.html | 176 ++++++ files/zh-cn/web/api/issecurecontext/index.html | 101 ++++ files/zh-cn/web/api/origin/index.html | 99 ++++ files/zh-cn/web/api/queuemicrotask/index.html | 109 ++++ files/zh-cn/web/api/setinterval/index.html | 636 +++++++++++++++++++++ files/zh-cn/web/api/settimeout/index.html | 477 ++++++++++++++++ .../api/windoworworkerglobalscope/atob/index.html | 75 --- .../api/windoworworkerglobalscope/btoa/index.html | 172 ------ .../windoworworkerglobalscope/caches/index.html | 127 ---- .../clearinterval/index.html | 75 --- .../cleartimeout/index.html | 151 ----- .../createimagebitmap/index.html | 207 ------- .../crossoriginisolated/index.html | 58 -- .../api/windoworworkerglobalscope/fetch/index.html | 173 ------ .../windoworworkerglobalscope/indexeddb/index.html | 175 ------ .../issecurecontext/index.html | 100 ---- .../windoworworkerglobalscope/origin/index.html | 98 ---- .../queuemicrotask/index.html | 108 ---- .../setinterval/index.html | 636 --------------------- .../settimeout/index.html | 477 ---------------- 28 files changed, 2640 insertions(+), 2632 deletions(-) create mode 100644 files/zh-cn/web/api/atob/index.html create mode 100644 files/zh-cn/web/api/btoa/index.html create mode 100644 files/zh-cn/web/api/caches/index.html create mode 100644 files/zh-cn/web/api/clearinterval/index.html create mode 100644 files/zh-cn/web/api/cleartimeout/index.html create mode 100644 files/zh-cn/web/api/createimagebitmap/index.html create mode 100644 files/zh-cn/web/api/crossoriginisolated/index.html create mode 100644 files/zh-cn/web/api/fetch/index.html create mode 100644 files/zh-cn/web/api/indexeddb/index.html create mode 100644 files/zh-cn/web/api/issecurecontext/index.html create mode 100644 files/zh-cn/web/api/origin/index.html create mode 100644 files/zh-cn/web/api/queuemicrotask/index.html create mode 100644 files/zh-cn/web/api/setinterval/index.html create mode 100644 files/zh-cn/web/api/settimeout/index.html delete mode 100644 files/zh-cn/web/api/windoworworkerglobalscope/atob/index.html delete mode 100644 files/zh-cn/web/api/windoworworkerglobalscope/btoa/index.html delete mode 100644 files/zh-cn/web/api/windoworworkerglobalscope/caches/index.html delete mode 100644 files/zh-cn/web/api/windoworworkerglobalscope/clearinterval/index.html delete mode 100644 files/zh-cn/web/api/windoworworkerglobalscope/cleartimeout/index.html delete mode 100644 files/zh-cn/web/api/windoworworkerglobalscope/createimagebitmap/index.html delete mode 100644 files/zh-cn/web/api/windoworworkerglobalscope/crossoriginisolated/index.html delete mode 100644 files/zh-cn/web/api/windoworworkerglobalscope/fetch/index.html delete mode 100644 files/zh-cn/web/api/windoworworkerglobalscope/indexeddb/index.html delete mode 100644 files/zh-cn/web/api/windoworworkerglobalscope/issecurecontext/index.html delete mode 100644 files/zh-cn/web/api/windoworworkerglobalscope/origin/index.html delete mode 100644 files/zh-cn/web/api/windoworworkerglobalscope/queuemicrotask/index.html delete mode 100644 files/zh-cn/web/api/windoworworkerglobalscope/setinterval/index.html delete mode 100644 files/zh-cn/web/api/windoworworkerglobalscope/settimeout/index.html (limited to 'files/zh-cn/web/api') diff --git a/files/zh-cn/web/api/atob/index.html b/files/zh-cn/web/api/atob/index.html new file mode 100644 index 0000000000..4679dec8c5 --- /dev/null +++ b/files/zh-cn/web/api/atob/index.html @@ -0,0 +1,75 @@ +--- +title: WindowOrWorkerGlobalScope.atob() +slug: Web/API/atob +tags: + - API + - Base64 + - DOM + - WindowOrWorkerGlobalScope + - atob + - 参考 + - 方法 +translation_of: Web/API/WindowOrWorkerGlobalScope/atob +original_slug: Web/API/WindowOrWorkerGlobalScope/atob +--- +

{{APIRef("HTML DOM")}}

+ +

WindowOrWorkerGlobalScope.atob() 对经过 base-64 编码的字符串进行解码。你可以使用 {{domxref("WindowBase64.btoa","window.btoa()")}} 方法来编码一个可能在传输过程中出现问题的数据,并且在接受数据之后,使用 atob() 方法再将数据解码。例如:你可以编码、传输和解码操作各种字符,比如 0-31 的 ASCII 码值。

+ +

关于针对 Unicode 或者 UTF-8 的应用方面,请查看 this note at Base64 encoding and decodingbtoa() 的备注

+ +

语法

+ +
var decodedData = scope.atob(encodedData);
+ +

异常

+ +

如果传入字符串不是有效的 base64 字符串,比如其长度不是 4 的倍数,则抛出{{jsxref("DOMException")}}。

+ +

示例

+ +
let encodedData = window.btoa("Hello, world"); // 编码
+let decodedData = window.atob(encodedData);    // 解码
+
+ +

规范

+ + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('HTML WHATWG', '#dom-windowbase64-atob', 'WindowBase64.atob()')}}{{Spec2('HTML WHATWG')}}No change since the latest snapshot, {{SpecName("HTML5.1")}}.
{{SpecName('HTML5.1', '#dom-windowbase64-atob', 'WindowBase64.atob()')}}{{Spec2('HTML5.1')}}Snapshot of {{SpecName("HTML WHATWG")}}. No change.
{{SpecName("HTML5 W3C", "#dom-windowbase64-atob", "WindowBase64.atob()")}}{{Spec2('HTML5 W3C')}}Snapshot of {{SpecName("HTML WHATWG")}}. Creation of WindowBase64 (properties were on the target before it).
+ +

浏览器兼容性

+ +

{{Compat("api.WindowOrWorkerGlobalScope.atob")}}

+ +

参见

+ + diff --git a/files/zh-cn/web/api/btoa/index.html b/files/zh-cn/web/api/btoa/index.html new file mode 100644 index 0000000000..1ff44702a1 --- /dev/null +++ b/files/zh-cn/web/api/btoa/index.html @@ -0,0 +1,172 @@ +--- +title: WindowOrWorkerGlobalScope.btoa() +slug: Web/API/btoa +tags: + - API + - Base64 + - Web + - WindowOrWorkerGlobalScope + - 参考 + - 字符串 + - 数据 + - 方法 +translation_of: Web/API/WindowOrWorkerGlobalScope/btoa +original_slug: Web/API/WindowOrWorkerGlobalScope/btoa +--- +

{{APIRef("HTML DOM")}}

+ +

WindowOrWorkerGlobalScope.btoa() 从 {{jsxref("String")}} 对象中创建一个 base-64 编码的 ASCII 字符串,其中字符串中的每个字符都被视为一个二进制数据字节。

+ +
+

Note: 由于这个函数将每个字符视为二进制数据的字节,而不管实际组成字符的字节数是多少,所以如果任何字符的{{Glossary("code point", "码位")}}超出 0x00 ~ 0xFF 这个范围,则会引发 InvalidCharacterError 异常。请参阅 {{anch("Unicode_字符串")}} ,该示例演示如何编码含有码位超出 0x00 ~ 0xFF 范围的字符的字符串。

+
+ +

语法

+ +
let encodedData = window.btoa(stringToEncode);
+
+ +

参数

+ +
+
stringToEncode
+
一个字符串, 其字符分别表示要编码为 ASCII 的二进制数据的单个字节。
+
+ +

返回值

+ +

一个包含 stringToEncode 的 Base64 表示的字符串。

+ +

示例

+ +
let encodedData = window.btoa("Hello, world"); // 编码
+let decodedData = window.atob(encodedData);    // 解码
+
+ +

备注

+ +

你可以使用此方法对可能导致通信问题的数据进行编码,传输,然后使用 {{domxref("WindowOrWorkerGlobalScope.atob","atob()")}} 方法再次解码数据。例如,可以编码控制字符,包括 ASCII 值为 0 到 31 的字符。

+ +

在用 JavaScript 编写 XPCOM 组件时,btoa() 方法也是可用的,虽然全局对象已经不是 {{domxref("Window")}} 了。

+ +

Unicode 字符串

+ +

在多数浏览器中,使用 btoa() 对 Unicode 字符串进行编码都会触发 InvalidCharacterError 异常。

+ +

一种选择是转义任何扩展字符,以便实际编码的字符串是原始字符的 ASCII 表示形式。考虑这个例子,代码来自 Johan Sundström

+ +
// ucs-2 string to base64 encoded ascii
+function utoa(str) {
+    return window.btoa(unescape(encodeURIComponent(str)));
+}
+// base64 encoded ascii to ucs-2 string
+function atou(str) {
+    return decodeURIComponent(escape(window.atob(str)));
+}
+// Usage:
+utoa('✓ à la mode'); // 4pyTIMOgIGxhIG1vZGU=
+atou('4pyTIMOgIGxhIG1vZGU='); // "✓ à la mode"
+
+utoa('I \u2661 Unicode!'); // SSDimaEgVW5pY29kZSE=
+atou('SSDimaEgVW5pY29kZSE='); // "I ♡ Unicode!"
+
+ +

更好、更可靠、性能更优异的解决方案是使用类型化数组进行转换。

+ +

规范

+ + + + + + + + + + + + + + + + + + + + + + + + + + +
规范状态备注
{{SpecName('HTML WHATWG', '#dom-btoa', 'WindowOrWorkerGlobalScope.btoa()')}}{{Spec2('HTML WHATWG')}}Method moved to the WindowOrWorkerGlobalScope mixin in the latest spec.
{{SpecName('HTML5.1', '#dom-windowbase64-btoa', 'WindowBase64.btoa()')}}{{Spec2('HTML5.1')}}Snapshot of {{SpecName("HTML WHATWG")}}. No change.
{{SpecName("HTML5 W3C", "#dom-windowbase64-btoa", "WindowBase64.btoa()")}}{{Spec2('HTML5 W3C')}}Snapshot of {{SpecName("HTML WHATWG")}}. Creation of WindowBase64 (properties where on the target before it).
+ +

Polyfill

+ +
// Polyfill from  https://github.com/MaxArt2501/base64-js/blob/master/base64.js
+(function() {
+    // base64 character set, plus padding character (=)
+    var b64 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",
+
+        // Regular expression to check formal correctness of base64 encoded strings
+        b64re = /^(?:[A-Za-z\d+\/]{4})*?(?:[A-Za-z\d+\/]{2}(?:==)?|[A-Za-z\d+\/]{3}=?)?$/;
+
+    window.btoa = window.btoa || function(string) {
+        string = String(string);
+        var bitmap, a, b, c,
+            result = "",
+            i = 0,
+            rest = string.length % 3; // To determine the final padding
+
+        for (; i < string.length;) {
+            if ((a = string.charCodeAt(i++)) > 255 ||
+                (b = string.charCodeAt(i++)) > 255 ||
+                (c = string.charCodeAt(i++)) > 255)
+                throw new TypeError("Failed to execute 'btoa' on 'Window': The string to be encoded contains characters outside of the Latin1 range.");
+
+            bitmap = (a << 16) | (b << 8) | c;
+            result += b64.charAt(bitmap >> 18 & 63) + b64.charAt(bitmap >> 12 & 63) +
+                b64.charAt(bitmap >> 6 & 63) + b64.charAt(bitmap & 63);
+        }
+
+        // If there's need of padding, replace the last 'A's with equal signs
+        return rest ? result.slice(0, rest - 3) + "===".substring(rest) : result;
+    };
+
+    window.atob = window.atob || function(string) {
+        // atob can work with strings with whitespaces, even inside the encoded part,
+        // but only \t, \n, \f, \r and ' ', which can be stripped.
+        string = String(string).replace(/[\t\n\f\r ]+/g, "");
+        if (!b64re.test(string))
+            throw new TypeError("Failed to execute 'atob' on 'Window': The string to be decoded is not correctly encoded.");
+
+        // Adding the padding if missing, for semplicity
+        string += "==".slice(2 - (string.length & 3));
+        var bitmap, result = "",
+            r1, r2, i = 0;
+        for (; i < string.length;) {
+            bitmap = b64.indexOf(string.charAt(i++)) << 18 | b64.indexOf(string.charAt(i++)) << 12 |
+                (r1 = b64.indexOf(string.charAt(i++))) << 6 | (r2 = b64.indexOf(string.charAt(i++)));
+
+            result += r1 === 64 ? String.fromCharCode(bitmap >> 16 & 255) :
+                r2 === 64 ? String.fromCharCode(bitmap >> 16 & 255, bitmap >> 8 & 255) :
+                String.fromCharCode(bitmap >> 16 & 255, bitmap >> 8 & 255, bitmap & 255);
+        }
+        return result;
+    };
+})()
+
+ +

浏览器兼容性

+ +

{{Compat("api.WindowOrWorkerGlobalScope.btoa")}}

+ +

参见

+ + diff --git a/files/zh-cn/web/api/caches/index.html b/files/zh-cn/web/api/caches/index.html new file mode 100644 index 0000000000..73c9fe5b30 --- /dev/null +++ b/files/zh-cn/web/api/caches/index.html @@ -0,0 +1,128 @@ +--- +title: WindowOrWorkerGlobalScope.caches +slug: Web/API/caches +translation_of: Web/API/WindowOrWorkerGlobalScope/caches +original_slug: Web/API/WindowOrWorkerGlobalScope/caches +--- +

{{APIRef()}}{{SeeCompatTable}}

+ +

caches 是{{domxref("WindowOrWorkerGlobalScope")}}接口的一个只读属性,它返回了与当前上下文紧密相关的{{domxref("CacheStorage")}}对象。此对象激活了诸如存储用于离线使用的资产,并生成对请求生成自定义响应等功能。

+ +

语法

+ +
var myCacheStorage = self.caches; // or just caches
+
+ +

+ +

{{domxref("CacheStorage")}} 对象.

+ +

例子

+ +

下面的例子展示了你在service worker上下文中如何应该运用cache对离线资产的进行存储。

+ +
this.addEventListener('install', function(event) {
+  event.waitUntil(
+    caches.open('v1').then(function(cache) {
+      return cache.addAll(
+        '/sw-test/',
+        '/sw-test/index.html',
+        '/sw-test/style.css',
+        '/sw-test/app.js',
+        '/sw-test/image-list.js',
+        '/sw-test/star-wars-logo.jpg',
+        '/sw-test/gallery/',
+        '/sw-test/gallery/bountyHunters.jpg',
+        '/sw-test/gallery/myLittleVader.jpg',
+        '/sw-test/gallery/snowTroopers.jpg'
+      );
+    })
+  );
+});
+ +

规范

+ + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('Service Workers', '#self-caches', 'caches')}}{{Spec2('Service Workers')}}Defined in a WindowOrWorkerGlobalScope partial in the newest spec.
{{SpecName('Service Workers')}}{{Spec2('Service Workers')}}Initial definition.
+ +

Browser compatibility

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support40.0{{CompatGeckoDesktop(42)}}
+ {{CompatGeckoDesktop(52)}}[1]
{{CompatNo}}{{CompatUnknown}}{{CompatNo}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatGeckoMobile(42)}}
+ {{CompatGeckoMobile(52)}}[1]
{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +

[1] caches 现在被定义在 {{domxref("WindowOrWorkerGlobalScope")}} 中的mixin里.

+ +

相关链接

+ + diff --git a/files/zh-cn/web/api/clearinterval/index.html b/files/zh-cn/web/api/clearinterval/index.html new file mode 100644 index 0000000000..3ba4544b4b --- /dev/null +++ b/files/zh-cn/web/api/clearinterval/index.html @@ -0,0 +1,75 @@ +--- +title: WindowTimers.clearInterval() +slug: Web/API/clearInterval +tags: + - API + - WindowOrWorkerGlobalScope + - 参考 + - 方法 +translation_of: Web/API/WindowOrWorkerGlobalScope/clearInterval +original_slug: Web/API/WindowOrWorkerGlobalScope/clearInterval +--- +
{{ApiRef("HTML DOM")}}
+ +

{{domxref("WindowOrWorkerGlobalScope")}} mixin 的 clearInterval() 方法可取消先前通过 {{domxref("WindowOrWorkerGlobalScope.setInterval", "setInterval()")}} 设置的重复定时任务。

+ +

语法

+ +
scope.clearInterval(intervalID)
+
+ +

Parameters

+ +
+
intervalID
+
要取消的定时器的 ID。是由 setInterval() 返回的。
+
+ +

值得一提的是,{{domxref("WindowOrWorkerGlobalScope.setInterval", "setInterval()")}} 和 {{domxref("WindowOrWorkerGlobalScope.setTimeout", "setTimeout()")}} 共用其定义的 IDs,即可以使用 clearInterval() 和 {{domxref("WindowOrWorkerGlobalScope.clearTimeout", "clearTimeout()")}} 中的任意一个。然而,为了使代码可读性更强,你应该尽量避免这种用法。

+ +

返回值

+ +

{{jsxref("undefined")}}

+ +

示例

+ +

查看 setInterval() 的示例

+ +

规范

+ + + + + + + + + + + + + + + + + + + +
规范状态备注
{{SpecName('HTML WHATWG', 'webappapis.html#dom-clearinterval', 'WindowOrWorkerGlobalScope.clearInterval()')}}{{Spec2("HTML WHATWG")}}Method moved to the WindowOrWorkerGlobalScope mixin in the latest spec.
{{SpecName('HTML WHATWG', 'webappapis.html#dom-clearinterval', 'clearInterval()')}}{{Spec2('HTML WHATWG')}}
+ +

浏览器兼容性

+ + + +

{{Compat("api.WindowOrWorkerGlobalScope.clearInterval")}}

+ +

参见

+ + diff --git a/files/zh-cn/web/api/cleartimeout/index.html b/files/zh-cn/web/api/cleartimeout/index.html new file mode 100644 index 0000000000..30648c48b7 --- /dev/null +++ b/files/zh-cn/web/api/cleartimeout/index.html @@ -0,0 +1,151 @@ +--- +title: WindowOrWorkerGlobalScope.clearTimeout() +slug: Web/API/clearTimeout +tags: + - API + - WindowOrWorkerGlobalScope + - clearTimeout +translation_of: Web/API/WindowOrWorkerGlobalScope/clearTimeout +original_slug: Web/API/WindowOrWorkerGlobalScope/clearTimeout +--- +
+
{{APIRef("HTML DOM")}}
+
+ +

{{domxref("WindowOrWorkerGlobalScope")}}内置的clearTimeout()方法取消了先前通过调用{{domxref("WindowOrWorkerGlobalScope.setTimeout", "setTimeout()")}}建立的定时器。

+ +

语法

+ +
scope.clearTimeout(timeoutID)
+ + + +

Parameters

+ +
+
timeoutID
+
您要取消定时器的标识符。 该ID由相应的setTimeout()调用返回。
+
+ +

值得注意的是,{{domxref("WindowOrWorkerGlobalScope.setTimeout", "setTimeout()")}}和{{domxref("WindowOrWorkerGlobalScope.setInterval", "setInterval()")}}使用共享的ID池, 意味着在技术上可以混用clearTimeout()和{{domxref("WindowOrWorkerGlobalScope.clearInterval", "clearInterval()")}} 。 但是,为了清楚起见,你应该避免这样做。

+ +

示例

+ +

在一个网页中运行如下脚本,并且点击一次页面。一秒钟后你会看见弹出一条信息。如果你在一秒内不停点击页面,弹出框将不再出现。

+ +
var alarm = {
+  remind: function(aMessage) {
+    alert(aMessage);
+    delete this.timeoutID;
+  },
+
+  setup: function() {
+    this.cancel();
+    var self = this;
+    this.timeoutID = window.setTimeout(function(msg) {self.remind(msg);}, 1000, "Wake up!");
+  },
+
+  cancel: function() {
+    if(typeof this.timeoutID == "number") {
+      window.clearTimeout(this.timeoutID);
+      delete this.timeoutID;
+    }
+  }
+};
+window.onclick = function() { alarm.setup() };
+ +

注意

+ +

传入一个错误的 ID 给 clearTimeout()不会有任何影响;也不会抛出异常。

+ +

规范

+ + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('HTML WHATWG', 'webappapis.html#dom-cleartimeout', 'WindowOrWorkerGlobalScope.clearTimeout()')}}{{Spec2("HTML WHATWG")}}Method moved to the WindowOrWorkerGlobalScope mixin in the latest spec.
{{SpecName('HTML WHATWG', 'webappapis.html#dom-cleartimeout', 'clearTimeout()')}}{{Spec2('HTML WHATWG')}}
+ +

浏览器兼容

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureChromeEdgeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support1.0{{CompatVersionUnknown}}{{CompatGeckoDesktop("1")}}
+ {{CompatGeckoDesktop("52")}}[1]
4.04.01.0
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidChrome for AndroidEdgeFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support1.01.0{{CompatVersionUnknown}}{{CompatGeckoMobile("1")}}
+ {{CompatGeckoMobile("52")}}[1]
6.06.01.0
+
+ +

[1] clearTimeout() now defined on {{domxref("WindowOrWorkerGlobalScope")}} mixin.

+ +

更多

+ + diff --git a/files/zh-cn/web/api/createimagebitmap/index.html b/files/zh-cn/web/api/createimagebitmap/index.html new file mode 100644 index 0000000000..c71c592551 --- /dev/null +++ b/files/zh-cn/web/api/createimagebitmap/index.html @@ -0,0 +1,208 @@ +--- +title: self.createImageBitmap() +slug: Web/API/createImageBitmap +translation_of: Web/API/WindowOrWorkerGlobalScope/createImageBitmap +original_slug: Web/API/WindowOrWorkerGlobalScope/createImageBitmap +--- +
{{APIRef("Canvas API")}}
+ +

createImageBitmap 方法存在 windows 和 workers 中. 它接受各种不同的图像来源, 并返回一个{{domxref("Promise")}}, resolve为{{domxref("ImageBitmap")}}. 可选地参数,图像被剪裁成自(sx,sy)且宽度为sw,高度为sh的像素的矩形。

+ +

Syntax

+ +
createImageBitmap(image[, options]).then(function(response) { ... });
+createImageBitmap(image, sx, sy, sw, sh[, options]).then(function(response) { ... });
+
+ +

Parameters

+ +
+
image
+
一个图像源, 可以是一个 {{HTMLElement("img")}}, SVG {{SVGElement("image")}}, {{HTMLElement("video")}}, {{HTMLElement("canvas")}}, {{domxref("HTMLImageElement")}}, {{domxref("SVGImageElement")}}, {{domxref("HTMLVideoElement")}}, {{domxref("HTMLCanvasElement")}}, {{domxref("Blob")}}, {{domxref("ImageData")}}, {{domxref("ImageBitmap")}}, 或 {{domxref("OffscreenCanvas")}} 对象.
+
sx
+
裁剪点x坐标.
+
sy
+
裁剪点y坐标.
+
sw
+
裁剪宽度,值可为负数.
+
sh
+
裁剪高度,值可为负数.
+
options {{optional_inline}}
+
为其设置选项的对象。可用的选项是: +
    +
  • imageOrientation: 指示图像是按原样呈现还是垂直翻转.  none (默认不翻转) 或 flipY.
  • +
  • premultiplyAlpha: 指示位图颜色通道由alpha通道预乘. 选择其一:none, premultiply, 或 default (默认).
  • +
  • colorSpaceConversion: 指示图像是否使用色彩空间转换进行解码. none 或 default (默认). The value default indicates that implementation-specific behavior is used.
  • +
  • resizeWidth: 指示新宽度的长整数。
  • +
  • resizeHeight: 指示新高度的长整数。
  • +
  • resizeQuality: 指定图像缩放算法. 选择其一pixelated, low (默认), medium, 或 high.
  • +
+
+
+ +

Return value

+ +

返回一个解决ImageBitmap的{{domxref("Promise")}} ,当Promise成功时resolves接收一个包含所得到的矩形的位图数据{{domxref("ImageBitmap")}}。

+ +

Example

+ +
var canvas = document.getElementById('myCanvas'),
+ctx = canvas.getContext('2d'),
+image = new Image();
+
+image.onload = function() {
+  Promise.all([
+    createImageBitmap(this, 0, 0, 32, 32),
+    createImageBitmap(this, 32, 0, 32, 32)
+  ]).then(function(sprites) {
+    ctx.drawImage(sprites[0], 0, 0);
+    ctx.drawImage(sprites[1], 32, 32);
+  });
+}
+
+image.src = 'sprites.png';
+
+ +

Specifications

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('HTML WHATWG', "webappapis.html#dom-createimagebitmap", "createImageBitmap")}}{{Spec2('HTML WHATWG')}} 
+ +

Browser compatibility

+ +

{{ CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)EdgeInternet ExplorerOperaSafari
Basic support{{CompatChrome(50)}} +

{{CompatGeckoDesktop(42)}}
+ {{CompatGeckoDesktop(52)}}[1]

+
{{CompatNo}}{{CompatNo}}{{CompatVersionUnknown}}{{CompatNo}}
options parameter{{CompatChrome(52)}}{{CompatUnknown}}{{CompatNo}}{{CompatNo}}39{{CompatNo}}
resizeWidth, resizeHeight, and resizeQuality{{CompatChrome(54)}}{{CompatUnknown}}{{CompatNo}}{{CompatNo}}{{CompatUnknown}}{{CompatNo}}
SVGImageElement as source image{{CompatChrome(59)}}{{CompatUnknown}}{{CompatNo}}{{CompatNo}}{{CompatUnknown}}{{CompatNo}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroid WebviewChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{CompatChrome(50)}}{{CompatChrome(50)}} +

{{CompatGeckomobile(42)}}
+ {{CompatGeckoMobile(52)}}[1]

+
{{CompatUnknown}}{{CompatVersionUnknown}}{{CompatUnknown}}
options parameter{{CompatChrome(52)}}{{CompatChrome(52)}}{{CompatUnknown}}{{CompatUnknown}}39{{CompatUnknown}}
resizeWidth, resizeHeight, and resizeQuality{{CompatChrome(54)}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}} 
SVGImageElement as source image{{CompatChrome(59)}}{{CompatChrome(59)}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
+
+ +

[1] createImageBitmap() now defined on {{domxref("WindowOrWorkerGlobalScope")}} mixin.

+ +

See also

+ + + +

+ +

diff --git a/files/zh-cn/web/api/crossoriginisolated/index.html b/files/zh-cn/web/api/crossoriginisolated/index.html new file mode 100644 index 0000000000..ff327d5d07 --- /dev/null +++ b/files/zh-cn/web/api/crossoriginisolated/index.html @@ -0,0 +1,59 @@ +--- +title: WindowOrWorkerGlobalScope.crossOriginIsolated +slug: Web/API/crossOriginIsolated +translation_of: Web/API/WindowOrWorkerGlobalScope/crossOriginIsolated +original_slug: Web/API/WindowOrWorkerGlobalScope/crossOriginIsolated +--- +
{{APIRef()}}{{SeeCompatTable}}
+ +

crossOriginIsolated 是 {{domxref("WindowOrWorkerGlobalScope")}} 的一个只读属性,返回一个布尔值,该值指示是否可以通过{{domxref("Window.postMessage()")}}调用发送 {{jsxref("SharedArrayBuffer")}}。

+ +

该值取决于响应中存在的{{httpheader("Cross-Origin-Opener-Policy")}} 和{{httpheader("Cross-Origin-Embedder-Policy")}} 头。

+ +

语法

+ +
var myCrossOriginIsolated = self.crossOriginIsolated; // 或直接 crossOriginIsolated
+
+ +

类型

+ +

布尔类型

+ +

示例

+ +
if(crossOriginIsolated) {
+  // post SharedArrayBuffer
+} else {
+  // Do something else
+}
+
+ +

规范

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName("HTML WHATWG")}}Not yet merged into the spec
+ +

浏览器兼容性

+ + + +

{{Compat("api.WindowOrWorkerGlobalScope.crossOriginIsolated")}}

+ +

参见

+ + diff --git a/files/zh-cn/web/api/fetch/index.html b/files/zh-cn/web/api/fetch/index.html new file mode 100644 index 0000000000..a1ee53fadf --- /dev/null +++ b/files/zh-cn/web/api/fetch/index.html @@ -0,0 +1,174 @@ +--- +title: WorkerOrGlobalScope.fetch() +slug: Web/API/fetch +tags: + - API + - Experimental + - Fetch + - FetchAPI + - GlobalFetch + - request +translation_of: Web/API/WindowOrWorkerGlobalScope/fetch +original_slug: Web/API/WindowOrWorkerGlobalScope/fetch +--- +

{{APIRef("Fetch")}}

+ +

位于 {{domxref("WorkerOrGlobalScope")}} 这一个 mixin 中的 fetch() 方法用于发起获取资源的请求。它返回一个 promise,这个 promise 会在请求响应后被 resolve,并传回 {{domxref("Response")}} 对象。

+ +

{{domxref("Window")}} 和 {{domxref("WorkerGlobalScope")}} 都实现了 WorkerOrGlobalScope。 ——这意味着基本在任何场景下只要你想获取资源,都可以使用 位于 WorkerOrGlobalScope 中的 fetch() 方法。

+ +

当遇到网络错误时,{{domxref("WorkerOrGlobalScope.fetch","fetch()")}} 返回的 promise 会被 reject,并传回 {{jsxref("TypeError")}},虽然这也可能因为权限或其它问题导致。成功的 fetch() 检查不仅要包括 promise 被 resolve,还要包括 {{domxref("Response.ok")}} 属性为 true。HTTP 404 状态并不被认为是网络错误。

+ +

fetch() 方法由 Content Security Policy 的 connect-src指令控制,而不是它请求的资源。

+ +
+

注意:{{domxref("WorkerOrGlobalScope.fetch","fetch()")}} 方法的参数与 {{domxref("Request.Request","Request()")}} 构造器是一样的。

+
+ +

语法

+ +
Promise<Response> fetch(input[, init]);
+
+ +

参数

+ +
+
?input
+
定义要获取的资源。这可能是: +
    +
  • 一个 {{domxref("USVString")}} 字符串,包含要获取资源的 URL。一些浏览器会接受 blob: 和 data: 作为 schemes.
  • +
  • 一个 {{domxref("Request")}} 对象。
  • +
+
+
init {{optional_inline}}
+
一个配置项对象,包括所有对请求的设置。可选的参数有: +
    +
  • method: 请求使用的方法,如 GETPOST。
  • +
  • headers: 请求的头信息,形式为 {{domxref("Headers")}} 的对象或包含 {{domxref("ByteString")}} 值的对象字面量。
  • +
  • body: 请求的 body 信息:可能是一个 {{domxref("Blob")}}、{{domxref("BufferSource")}}、{{domxref("FormData")}}、{{domxref("URLSearchParams")}} 或者 {{domxref("USVString")}} 对象。注意 GET 或 HEAD 方法的请求不能包含 body 信息。
  • +
  • mode: 请求的模式,如 cors、 no-cors 或者 same-origin。
  • +
  • credentials: 请求的 credentials,如 omitsame-origin 或者 include。为了在当前域名内自动发送 cookie , 必须提供这个选项, 从 Chrome 50 开始, 这个属性也可以接受 {{domxref("FederatedCredential")}} 实例或是一个 {{domxref("PasswordCredential")}} 实例。
  • +
  • cache:  请求的 cache 模式: default、 no-storereload 、 no-cache 、 force-cache 或者 only-if-cached
  • +
  • redirect: 可用的 redirect 模式: follow (自动重定向), error (如果产生重定向将自动终止并且抛出一个错误), 或者 manual (手动处理重定向). 在Chrome中默认使用follow(Chrome 47之前的默认值是manual)。
  • +
  • referrer: 一个 {{domxref("USVString")}} 可以是 no-referrerclient或一个 URL。默认是 client。
  • +
  • referrerPolicy: 指定了HTTP头部referer字段的值。可能为以下值之一: no-referrer、 no-referrer-when-downgrade、 origin、 origin-when-cross-origin、 unsafe-url 。
  • +
  • integrity: 包括请求的  subresource integrity 值 ( 例如: sha256-BpfBw7ivV8q2jLiT13fxDYAe2tJllusRSZ273h2nFSE=)。
  • +
+
+
+ +

返回值

+ +

一个 {{jsxref("Promise")}},resolve 时回传 {{domxref("Response")}} 对象。

+ +

例外

+ + + + + + + + + + + + + + + + + + +
类型描述
AbortError请求被{{domxref("AbortController.abort()")}}终止。
TypeErrorFirefox 43开始,如果fetch()接收到含有用户名和密码的URL(例如http://user:password@example.com),它将会抛出一个TypeError
+ +

示例

+ +

Fetch Request 示例 (参见 Fetch Request live) 中,我们使用对应的构造器创建了一个新的 {{domxref("Request")}} 对象,然后调用 fetch() 方法获取资源。因为我们是在请求一个图片,为了解析正常,我们对响应执行 {{domxref("Body.blob")}} 来设置相应的 MIME 类型。然后创建一个 Object URL,并在 {{htmlelement("img")}} 元素中把它显示出来。

+ +
var myImage = document.querySelector('img');
+
+var myRequest = new Request('flowers.jpg');
+
+fetch(myRequest).then(function(response) {
+  return response.blob();
+}).then(function(response) {
+  var objectURL = URL.createObjectURL(response);
+  myImage.src = objectURL;
+});
+ +

在 Fetch with init then Request 示例 (参见 Fetch Request init live) 中,我们做同样的操作,除了在调用 fetch() 时传入一个 init 对象:

+ +
var myImage = document.querySelector('img');
+
+var myHeaders = new Headers();
+myHeaders.append('Content-Type', 'image/jpeg');
+
+var myInit = { method: 'GET',
+               headers: myHeaders,
+               mode: 'cors',
+               cache: 'default' };
+
+var myRequest = new Request('flowers.jpg');
+
+fetch(myRequest,myInit).then(function(response) {
+  ...
+});
+ +

你也可以传入同样的 init 对象到 Request 构造器,来实现同样的效果,如:

+ +
var myRequest = new Request('flowers.jpg',myInit);
+
+ +

init 对象中的 headers 也可以是一个对象字面量:

+ +
var myInit = { method: 'GET',
+               headers: {
+                   'Content-Type': 'image/jpeg'
+               },
+               mode: 'cors',
+               cache: 'default' };
+
+var myRequest = new Request('flowers.jpg', myInit);
+ +

规范

+ + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('Fetch','#fetch-method','fetch()')}}{{Spec2('Fetch')}}Defined in a WindowOrWorkerGlobalScope partial in the newest spec.
{{SpecName('Fetch','#dom-global-fetch','fetch()')}}{{Spec2('Fetch')}}Initial definition
{{SpecName('Credential Management')}}{{Spec2('Credential Management')}}Adds {{domxref("FederatedCredential")}} or {{domxref("PasswordCredential")}} instance as a possible value for init.credentials.
+ +

浏览器兼容性

+ + + +

{{Compat("api.WindowOrWorkerGlobalScope.fetch")}}

+ +

相关链接

+ + diff --git a/files/zh-cn/web/api/indexeddb/index.html b/files/zh-cn/web/api/indexeddb/index.html new file mode 100644 index 0000000000..baf7f0c1b9 --- /dev/null +++ b/files/zh-cn/web/api/indexeddb/index.html @@ -0,0 +1,176 @@ +--- +title: WindowOrWorkerGlobalScope.indexedDB +slug: Web/API/indexedDB +tags: + - API + - Database + - IndexedDB + - Reference + - Storage + - WindowOrWorkerGlobalScope + - 参考 + - 属性 +translation_of: Web/API/WindowOrWorkerGlobalScope/indexedDB +original_slug: Web/API/WindowOrWorkerGlobalScope/indexedDB +--- +

{{ APIRef() }}

+ +

indexedDB 是 {{domxref("WindowOrWorkerGlobalScope")}}的一个只读属性,它集成了为应用程序提供异步访问索引数据库的功能的机制。.

+ +

语法

+ +
var IDBFactory = self.indexedDB;
+ +
+

+
+ +

一个 {{domxref("IDBFactory")}} 对象.

+ +

示例

+ +
var db;
+function openDB() {
+ var DBOpenRequest = window.indexedDB.open('toDoList');
+ DBOpenRequest.onsuccess = function(e) {
+   db = DBOpenRequest.result;
+ }
+}
+ +

规范

+ + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('IndexedDB 2', '#dom-windoworworkerglobalscope-indexeddb', 'indexedDB')}}{{Spec2('IndexedDB 2')}}Defined in a WindowOrWorkerGlobalScope partial in the newest spec.
{{SpecName('IndexedDB', '#widl-IDBEnvironment-indexedDB', 'indexedDB')}}{{Spec2('IndexedDB')}}Initial definition.
+ +

浏览器兼容性

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureChromeEdgeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Basic support23{{property_prefix("webkit")}}
+ 24
{{CompatVersionUnknown}}10 {{property_prefix("moz")}}
+ {{CompatGeckoDesktop("16.0")}}
+ {{CompatGeckoDesktop("52.0")}}[1]
10, partial157.1
Available in workers{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatGeckoMobile("37.0")}}{{CompatUnknown}}{{CompatVersionUnknown}}{{CompatUnknown}}
Indexed Database 2.0{{CompatChrome(58)}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatOpera(45)}}{{CompatUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroid WebviewChrome for AndroidEdgeFirefox Mobile (Gecko)Firefox OSIE PhoneOpera MobileSafari Mobile
Basic support{{CompatVersionUnknown}}{{CompatUnknown}}{{CompatVersionUnknown}}{{CompatGeckoMobile("22.0")}}
+ {{CompatGeckoMobile("52.0")}}[1]
1.0.110228
Available in workers{{CompatVersionUnknown}}{{CompatUnknown}}{{CompatVersionUnknown}}{{CompatGeckoMobile("37.0")}}{{CompatVersionUnknown}}{{CompatUnknown}}{{CompatVersionUnknown}}{{CompatUnknown}}
Indexed Database 2.0{{CompatChrome(58)}}{{CompatChrome(58)}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatOperaMobile(45)}}{{CompatUnknown}}
+
+ +

[1] indexedDB 定义在 {{domxref("WindowOrWorkerGlobalScope")}} mixin(一种实现多继承的方法)上.

+ +

相关链接

+ + diff --git a/files/zh-cn/web/api/issecurecontext/index.html b/files/zh-cn/web/api/issecurecontext/index.html new file mode 100644 index 0000000000..355b4dcde6 --- /dev/null +++ b/files/zh-cn/web/api/issecurecontext/index.html @@ -0,0 +1,101 @@ +--- +title: WindowOrWorkerGlobalScope.isSecureContext +slug: Web/API/isSecureContext +tags: + - API + - Property + - Reference + - Window + - WindowOrWorkerGlobalContext + - Workers + - isSecureContext +translation_of: Web/API/WindowOrWorkerGlobalScope/isSecureContext +original_slug: Web/API/WindowOrWorkerGlobalScope/isSecureContext +--- +

{{APIRef()}}{{SeeCompatTable}}

+ +

isSecureContext 是 {{domxref("WindowOrWorkerGlobalScope")}} 的一个只读属性,返回一个布尔值,标识当前上下文是否安全,安全(true)或不安全(false)。

+ +

语法

+ +
var isItSecure = self.isSecureContext; // 或者直接使用 isSecureContext
+
+ +

类型

+ +

 {{domxref("Boolean")}}.

+ +

规范

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('Secure Contexts', 'webappapis.html#dom-origin', 'WindowOrWorkerGlobalScope.isSecureContext')}}{{Spec2('Secure Contexts')}}Initial definition.
+ +

浏览器兼容性

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support{{CompatChrome(55)}}{{CompatGeckoDesktop(52)}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureAndroid WebviewChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{CompatChrome(55)}}{{CompatChrome(55)}}{{CompatGeckoMobile(52)}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
+
+ +

参考

+ + diff --git a/files/zh-cn/web/api/origin/index.html b/files/zh-cn/web/api/origin/index.html new file mode 100644 index 0000000000..eeb79e7cf3 --- /dev/null +++ b/files/zh-cn/web/api/origin/index.html @@ -0,0 +1,99 @@ +--- +title: WindowOrWorkerGlobalScope.origin +slug: Web/API/origin +tags: + - global scope + - origin + - serialized +translation_of: Web/API/WindowOrWorkerGlobalScope/origin +original_slug: Web/API/WindowOrWorkerGlobalScope/origin +--- +

{{APIRef()}}{{SeeCompatTable}}{{domxref("WindowOrWorkerGlobalScope")}} 接口的 origin 只读属性返回全局范围的 origin, 序列化为一个字符串。

+ +

Syntax

+ +
let myOrigin = self.origin; // or just origin
+
+ +

Value

+ +

A {{domxref("USVString")}}.

+ +

Examples

+ +

Executed from inside a worker script, the following snippet will log the worker's global scope's origin to the console each time it receives a message

+ +
onmessage = function() {
+  console.log(self.origin);
+};
+ +

If the origin is not a scheme/host/port tuple (say you are trying to run it locally, i.e. via file:// URL), origin will return the string "null".

+ +

Specifications

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('HTML WHATWG', 'webappapis.html#dom-origin', 'WindowOrWorkerGlobalScope.origin')}}{{Spec2('HTML WHATWG')}}Initial definition.
+ +

Browser compatibility

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support{{CompatChrome(59)}}{{CompatGeckoDesktop(54)}}{{CompatNo}}{{CompatNo}}{{CompatNo}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{CompatChrome(59)}}{{CompatChrome(59)}}{{CompatGeckoMobile(54)}} {{CompatNo}}{{CompatNo}}{{CompatNo}}
+
diff --git a/files/zh-cn/web/api/queuemicrotask/index.html b/files/zh-cn/web/api/queuemicrotask/index.html new file mode 100644 index 0000000000..9079205222 --- /dev/null +++ b/files/zh-cn/web/api/queuemicrotask/index.html @@ -0,0 +1,109 @@ +--- +title: WindowOrWorkerGlobalScope.queueMicrotask() +slug: Web/API/queueMicrotask +tags: + - API + - JavaScript + - Method + - Microtask + - 参考 + - 同步 + - 方法 +translation_of: Web/API/WindowOrWorkerGlobalScope/queueMicrotask +original_slug: Web/API/WindowOrWorkerGlobalScope/queueMicrotask +--- +
{{APIRef("HTML DOM")}}
+ +
{{domxref("Window")}} 或 {{domxref("Worker")}} 接口的 queueMicrotask() 方法,queues a microtask to be executed at a safe time prior to control returning to the browser's event loop.microtask 是一个简短的函数,它将在当前任务(task)完成其工作之后运行,并且在执行上下文的控制返回到浏览器的事件循环之前,没有其他代码等待运行。The microtask is a short function which will run after the current task has completed its work and when there is no other code waiting to be run before control of the execution context is returned to the browser's event loop.
+ +
+ +

This lets your code run without interfering with any other, potentially higher priority, code that is pending, but before the browser regains control over the execution context, potentially depending on work you need to complete. You can learn more about how to use microtasks and why you might choose to do so in our microtask guide.

+ +

The importance of microtasks comes in its ability to perform tasks asynchronously but in a specific order. See Using microtasks in JavaScript with queueMicrotask() for more details.

+ +

Microtasks are especially useful for libraries and frameworks that need to perform final cleanup or other just-before-rendering tasks.

+ +

queueMicrotask() 处于 {{domxref("WindowOrWorkerGlobalScope")}} mixin 之下。

+ +

语法

+ +
scope.queueMicrotask(function);
+
+ +

参数

+ +
+
function
+
A {{jsxref("function")}} to be executed when the browser engine determines it is safe to call your code.微任务(microtask)的执行顺序在所有挂起的任务(pending tasks)完成之后,在对浏览器的事件循环产生控制(yielding control to the browser's event loop)之前。
+
+ +

返回值

+ +

undefined

+ +

示例

+ +
self.queueMicrotask(() => {
+  // 函数的内容
+})
+ +

来自 queueMicrotask 的规范文档:

+ +
MyElement.prototype.loadData = function (url) {
+  if (this._cache[url]) {
+    queueMicrotask(() => {
+      this._setData(this._cache[url]);
+      this.dispatchEvent(new Event("load"));
+    });
+  } else {
+    fetch(url).then(res => res.arrayBuffer()).then(data => {
+      this._cache[url] = data;
+      this._setData(data);
+      this.dispatchEvent(new Event("load"));
+    });
+  }
+};
+ +

polyfill

+ +

下面的代码是一份 queueMicrotask() 的 polyfill。它通过使用立即 resolve 的 promise 创建一个微任务(microtask),如果无法创建 promise,则回落(fallback)到使用setTimeout()

+ +
if (typeof window.queueMicrotask !== "function") {
+  window.queueMicrotask = function (callback) {
+    Promise.resolve()
+      .then(callback)
+      .catch(e => setTimeout(() => { throw e; }));
+  };
+}
+
+ +

规范

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName("HTML WHATWG", "timers-and-user-prompts.html#microtask-queuing", "self.queueMicrotask()")}}{{Spec2("HTML WHATWG")}}Initial definition
+ +

浏览器兼容性

+ +

{{Compat("api.WindowOrWorkerGlobalScope.queueMicrotask")}}

+ +

参见

+ + diff --git a/files/zh-cn/web/api/setinterval/index.html b/files/zh-cn/web/api/setinterval/index.html new file mode 100644 index 0000000000..f3401fc5a5 --- /dev/null +++ b/files/zh-cn/web/api/setinterval/index.html @@ -0,0 +1,636 @@ +--- +title: window.setInterval +slug: Web/API/setInterval +tags: + - API + - DOM + - 定时 + - 方法 + - 时间 +translation_of: Web/API/WindowOrWorkerGlobalScope/setInterval +original_slug: Web/API/WindowOrWorkerGlobalScope/setInterval +--- +
{{ ApiRef("HTML DOM") }}
+ +

{{domxref("WindowOrWorkerGlobalScope")}} 的 setInterval() 方法重复调用一个函数或执行一个代码段,在每次调用之间具有固定的时间延迟。

+ +

在窗口和工作接口上提供的setInterval()方法重复调用函数或执行代码片段,每次调用之间有固定的时间延迟。它返回一个时间间隔ID,该ID唯一地标识时间间隔,因此您可以稍后通过调用clearInterval()来删除它。这个方法是由WindowOrWorkerGlobalScope mixin定义的。

+ +

语法

+ +
var intervalID = scope.setInterval(func, delay, [arg1, arg2, ...]);
+var intervalID = scope.setInterval(code, delay);
+
+ +

参数

+ +
+
func
+
要重复调用的函数。 每经过指定 延迟 毫秒后执行的{{jsxref("函数")}} 。该函数不接受任何参数,也没有返回值。
+
code
+
这个语法是可选的,你可以传递一个字符串来代替一个函数对象,你传递的字符串会被编译然后每个delay毫秒时间内执行一次。这个语法因为存在安全风险所以不被推荐使用。
+
delay
+
是每次延迟的毫秒数 (一秒等于1000毫秒),函数的每次调用会在该延迟之后发生。和setTimeout一样,实际的延迟时间可能会稍长一点。这个时间计算单位是毫秒(千分之一秒),这个定时器会使指定方法或者代码段执行的时候进行时间延迟。如果这个参数值小于10,则默认使用值为10。请注意,真正延迟时间或许更长; 请参考示例: {{SectionOnPage("/en-US/docs/Web/API/WindowOrWorkerGlobalScope/setTimeout", "Reasons for delays longer than specified")}} 
+
arg1, ..., argN {{optional_inline}}
+
当定时器过期的时候,将被传递给func指定函数的附加参数。
+
+ +

返回值

+ +

此返回值intervalID是一个非零数值,用来标识通过setInterval()创建的计时器,这个值可以用来作为clearInterval()的参数来清除对应的计时器 。

+ +

值得注意的是,setInterval()setTimeout()共享同一个ID池,并且clearInterval()clearTimeout()在技术上是可互换使用的。但是,我们必须去匹配clearInterval()clearTimeout()对应的id,以避免代码杂乱无章,增强代码的可维护性。

+ +
Note: The delay argument is converted to a signed 32-bit integer. This effectively limits delay to 2147483647 ms, since it's specified as a signed integer in the IDL.
+ +

示例

+ +

例1:基本用法

+ +

下面例子是 setInterval()的基本语法

+ +
var intervalID = window.setInterval(myCallback, 500, 'Parameter 1', 'Parameter 2');
+
+function myCallback(a, b)
+{
+ // Your code here
+ // Parameters are purely optional.
+ console.log(a);
+ console.log(b);
+}
+
+ +

例2:两种颜色的切换

+ +

下面的例子里会每隔一秒就调用函数 flashtext() 一次,直至你通过按下 Stop 按钮来清除本次重复操作的唯一辨识符 intervalID

+ +
<!DOCTYPE html>
+<html>
+<head>
+  <meta charset="UTF-8" />
+  <title>setInterval/clearInterval example</title>
+
+  <script>
+    var nIntervId;
+
+    function changeColor() {
+      nIntervId = setInterval(flashText, 1000);
+    }
+
+    function flashText() {
+      var oElem = document.getElementById('my_box');
+      oElem.style.color = oElem.style.color == 'red' ? 'blue' : 'red';
+      // oElem.style.color == 'red' ? 'blue' : 'red' is a ternary operator.
+    }
+
+    function stopTextColor() {
+      clearInterval(nIntervId);
+    }
+  </script>
+</head>
+
+<body onload="changeColor();">
+  <div id="my_box">
+    <p>Hello World</p>
+  </div>
+
+  <button onclick="stopTextColor();">Stop</button>
+</body>
+</html>
+
+ +

例3:打字机效果

+ +

下面这个例子通过键入、删除和再次键入所有 NodeList 中的符合特定的选择器的字符,以达到打字机的效果。

+ +
+
<!DOCTYPE html>
+<html>
+<head>
+<meta charset="UTF-8" />
+<title>JavaScript Typewriter - MDN Example</title>
+<script>
+function Typewriter (sSelector, nRate) {
+
+  function clean () {
+    clearInterval(nIntervId);
+    bTyping = false;
+    bStart = true;
+    oCurrent = null;
+    aSheets.length = nIdx = 0;
+  }
+
+  function scroll (oSheet, nPos, bEraseAndStop) {
+    if (!oSheet.hasOwnProperty("parts") || aMap.length < nPos) { return true; }
+
+    var oRel, bExit = false;
+
+    if (aMap.length === nPos) { aMap.push(0); }
+
+    while (aMap[nPos] < oSheet.parts.length) {
+      oRel = oSheet.parts[aMap[nPos]];
+
+      scroll(oRel, nPos + 1, bEraseAndStop) ? aMap[nPos]++ : bExit = true;
+
+      if (bEraseAndStop && (oRel.ref.nodeType - 1 | 1) === 3 && oRel.ref.nodeValue) {
+        bExit = true;
+        oCurrent = oRel.ref;
+        sPart = oCurrent.nodeValue;
+        oCurrent.nodeValue = "";
+      }
+
+      oSheet.ref.appendChild(oRel.ref);
+      if (bExit) { return false; }
+    }
+
+    aMap.length--;
+    return true;
+  }
+
+  function typewrite () {
+    if (sPart.length === 0 && scroll(aSheets[nIdx], 0, true) && nIdx++ === aSheets.length - 1) { clean(); return; }
+
+    oCurrent.nodeValue += sPart.charAt(0);
+    sPart = sPart.slice(1);
+  }
+
+  function Sheet (oNode) {
+    this.ref = oNode;
+    if (!oNode.hasChildNodes()) { return; }
+    this.parts = Array.prototype.slice.call(oNode.childNodes);
+
+    for (var nChild = 0; nChild < this.parts.length; nChild++) {
+      oNode.removeChild(this.parts[nChild]);
+      this.parts[nChild] = new Sheet(this.parts[nChild]);
+    }
+  }
+
+  var
+    nIntervId, oCurrent = null, bTyping = false, bStart = true,
+    nIdx = 0, sPart = "", aSheets = [], aMap = [];
+
+  this.rate = nRate || 100;
+
+  this.play = function () {
+    if (bTyping) { return; }
+    if (bStart) {
+      var aItems = document.querySelectorAll(sSelector);
+
+      if (aItems.length === 0) { return; }
+      for (var nItem = 0; nItem < aItems.length; nItem++) {
+        aSheets.push(new Sheet(aItems[nItem]));
+        /* Uncomment the following line if you have previously hidden your elements via CSS: */
+        // aItems[nItem].style.visibility = "visible";
+      }
+
+      bStart = false;
+    }
+
+    nIntervId = setInterval(typewrite, this.rate);
+    bTyping = true;
+  };
+
+  this.pause = function () {
+    clearInterval(nIntervId);
+    bTyping = false;
+  };
+
+  this.terminate = function () {
+    oCurrent.nodeValue += sPart;
+    sPart = "";
+    for (nIdx; nIdx < aSheets.length; scroll(aSheets[nIdx++], 0, false));
+    clean();
+  };
+}
+
+/* usage: */
+var oTWExample1 = new Typewriter(/* elements: */ "#article, h1, #info, #copyleft", /* frame rate (optional): */ 15);
+
+/* default frame rate is 100: */
+var oTWExample2 = new Typewriter("#controls");
+
+/* you can also change the frame rate value modifying the "rate" property; for example: */
+// oTWExample2.rate = 150;
+
+onload = function () {
+  oTWExample1.play();
+  oTWExample2.play();
+};
+</script>
+<style type="text/css">
+span.intLink, a, a:visited {
+  cursor: pointer;
+  color: #000000;
+  text-decoration: underline;
+}
+
+#info {
+  width: 180px;
+  height: 150px;
+  float: right;
+  background-color: #eeeeff;
+  padding: 4px;
+  overflow: auto;
+  font-size: 12px;
+  margin: 4px;
+  border-radius: 5px;
+  /* visibility: hidden; */
+}
+</style>
+</head>
+
+<body>
+
+<p id="copyleft" style="font-style: italic; font-size: 12px; text-align: center;">CopyLeft 2012 by <a href="https://developer.mozilla.org/" target="_blank">Mozilla Developer Network</a></p>
+<p id="controls" style="text-align: center;">[&nbsp;<span class="intLink" onclick="oTWExample1.play();">Play</span> | <span class="intLink" onclick="oTWExample1.pause();">Pause</span> | <span class="intLink" onclick="oTWExample1.terminate();">Terminate</span>&nbsp;]</p>
+<div id="info">
+Vivamus blandit massa ut metus mattis in fringilla lectus imperdiet. Proin ac ante a felis ornare vehicula. Fusce pellentesque lacus vitae eros convallis ut mollis magna pellentesque. Pellentesque placerat enim at lacus ultricies vitae facilisis nisi fringilla. In tincidunt tincidunt tincidunt.
+</div>
+<h1>JavaScript Typewriter</h1>
+
+<div id="article">
+<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nullam ultrices dolor ac dolor imperdiet ullamcorper. Suspendisse quam libero, luctus auctor mollis sed, malesuada condimentum magna. Quisque in ante tellus, in placerat est. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Donec a mi magna, quis mattis dolor. Etiam sit amet ligula quis urna auctor imperdiet nec faucibus ante. Mauris vel consectetur dolor. Nunc eget elit eget velit pulvinar fringilla consectetur aliquam purus. Curabitur convallis, justo posuere porta egestas, velit erat ornare tortor, non viverra justo diam eget arcu. Phasellus adipiscing fermentum nibh ac commodo. Nam turpis nunc, suscipit a hendrerit vitae, volutpat non ipsum.</p>
+<form>
+<p>Phasellus ac nisl lorem: <input type="text" /><br />
+<textarea style="width: 400px; height: 200px;">Nullam commodo suscipit lacus non aliquet. Phasellus ac nisl lorem, sed facilisis ligula. Nam cursus lobortis placerat. Sed dui nisi, elementum eu sodales ac, placerat sit amet mauris. Pellentesque dapibus tellus ut ipsum aliquam eu auctor dui vehicula. Quisque ultrices laoreet erat, at ultrices tortor sodales non. Sed venenatis luctus magna, ultricies ultricies nunc fringilla eget. Praesent scelerisque urna vitae nibh tristique varius consequat neque luctus. Integer ornare, erat a porta tempus, velit justo fermentum elit, a fermentum metus nisi eu ipsum. Vivamus eget augue vel dui viverra adipiscing congue ut massa. Praesent vitae eros erat, pulvinar laoreet magna. Maecenas vestibulum mollis nunc in posuere. Pellentesque sit amet metus a turpis lobortis tempor eu vel tortor. Cras sodales eleifend interdum.</textarea></p>
+<input type="submit" value="Send" />
+</form>
+<p>Duis lobortis sapien quis nisl luctus porttitor. In tempor semper libero, eu tincidunt dolor eleifend sit amet. Ut nec velit in dolor tincidunt rhoncus non non diam. Morbi auctor ornare orci, non euismod felis gravida nec. Curabitur elementum nisi a eros rutrum nec blandit diam placerat. Aenean tincidunt risus ut nisi consectetur cursus. Ut vitae quam elit. Donec dignissim est in quam tempor consequat. Aliquam aliquam diam non felis convallis suscipit. Nulla facilisi. Donec lacus risus, dignissim et fringilla et, egestas vel eros. Duis malesuada accumsan dui, at fringilla mauris bibStartum quis. Cras adipiscing ultricies fermentum. Praesent bibStartum condimentum feugiat.</p>
+<p>Nam faucibus, ligula eu fringilla pulvinar, lectus tellus iaculis nunc, vitae scelerisque metus leo non metus. Proin mattis lobortis lobortis. Quisque accumsan faucibus erat, vel varius tortor ultricies ac. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed nec libero nunc. Nullam tortor nunc, elementum a consectetur et, ultrices eu orci. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Pellentesque a nisl eu sem vehicula egestas.</p>
+</div>
+</body>
+</html>
+
+ +

查看示例效果,亦可参考:clearInterval()

+ +

回调参数

+ +

如前所述,Internet Explorer 9及以下版本不支持在setTimeout()setInterval()中向回调函数传递参数。下面的IE专用代码演示了一种克服这种限制的方法。使用时,只需将以下代码添加到你的脚本顶部即可。

+ +
/*\
+|*|
+|*|  IE-specific polyfill that enables the passage of arbitrary arguments to the
+|*|  callback functions of javascript timers (HTML5 standard syntax).
+|*|
+|*|  https://developer.mozilla.org/en-US/docs/Web/API/window.setInterval
+|*|  https://developer.mozilla.org/User:fusionchess
+|*|
+|*|  Syntax:
+|*|  var timeoutID = window.setTimeout(func, delay[, arg1, arg2, ...]);
+|*|  var timeoutID = window.setTimeout(code, delay);
+|*|  var intervalID = window.setInterval(func, delay[, arg1, arg2, ...]);
+|*|  var intervalID = window.setInterval(code, delay);
+|*|
+\*/
+
+if (document.all && !window.setTimeout.isPolyfill) {
+  var __nativeST__ = window.setTimeout;
+  window.setTimeout = function (vCallback, nDelay /*, argumentToPass1, argumentToPass2, etc. */) {
+    var aArgs = Array.prototype.slice.call(arguments, 2);
+    return __nativeST__(vCallback instanceof Function ? function () {
+      vCallback.apply(null, aArgs);
+    } : vCallback, nDelay);
+  };
+  window.setTimeout.isPolyfill = true;
+}
+
+if (document.all && !window.setInterval.isPolyfill) {
+  var __nativeSI__ = window.setInterval;
+  window.setInterval = function (vCallback, nDelay /*, argumentToPass1, argumentToPass2, etc. */) {
+    var aArgs = Array.prototype.slice.call(arguments, 2);
+    return __nativeSI__(vCallback instanceof Function ? function () {
+      vCallback.apply(null, aArgs);
+    } : vCallback, nDelay);
+  };
+  window.setInterval.isPolyfill = true;
+}
+
+ +

另一种方式是使用匿名函数调用你的回调函数,但是这种方式开销较大。例如:

+ +
var intervalID = setInterval(function() { myFunc('one', 'two', 'three'); }, 1000);
+ +

还有一种方式是使用 function's bind. 例如:

+ +
var intervalID = setInterval(function(arg1) {}.bind(undefined, 10), 1000);
+ +

{{h3_gecko_minversion("Inactive tabs", "5.0")}}

+ +

Starting in Gecko 5.0 {{geckoRelease("5.0")}}, intervals are clamped to fire no more often than once per second in inactive tabs.

+ +

"this" 的问题

+ +

当你给 setInterval() 传递一个方法或者函数的时候,this 值的绑定会存在一些问题。  这个问题在JavaScript 参考 进行了详细解释。

+ +

解释

+ +

Code executed by setInterval() runs in a separate execution context than the function from which it was called. As a consequence, the this keyword for the called function is set to the window (or global) object, it is not the same as the this value for the function that called setTimeout. See the following example (which uses setTimeout() instead of setInterval() – the problem, in fact, is the same for both timers):

+ +
myArray = ['zero', 'one', 'two'];
+
+myArray.myMethod = function (sProperty) {
+    alert(arguments.length > 0 ? this[sProperty] : this);
+};
+
+myArray.myMethod(); // prints "zero,one,two"
+myArray.myMethod(1); // prints "one"
+setTimeout(myArray.myMethod, 1000); // prints "[object Window]" after 1 second
+setTimeout(myArray.myMethod, 1500, "1"); // prints "undefined" after 1,5 seconds
+// passing the 'this' object with .call won't work
+// because this will change the value of this inside setTimeout itself
+// while we want to change the value of this inside myArray.myMethod
+// in fact, it will be an error because setTimeout code expects this to be the window object:
+setTimeout.call(myArray, myArray.myMethod, 2000); // error: "NS_ERROR_XPC_BAD_OP_ON_WN_PROTO: Illegal operation on WrappedNative prototype object"
+setTimeout.call(myArray, myArray.myMethod, 2500, 2); // same error
+
+ +

As you can see there are no ways to pass the this object to the callback function in the legacy JavaScript.

+ +

一个可能的解决方案

+ +

A possible way to solve the "this" problem is to replace the two native setTimeout() or setInterval() global functions with two non-native ones that enable their invocation through the Function.prototype.call method. The following example shows a possible replacement:

+ +
// Enable the passage of the 'this' object through the JavaScript timers
+
+var __nativeST__ = window.setTimeout, __nativeSI__ = window.setInterval;
+
+window.setTimeout = function (vCallback, nDelay /*, argumentToPass1, argumentToPass2, etc. */) {
+  var oThis = this, aArgs = Array.prototype.slice.call(arguments, 2);
+  return __nativeST__(vCallback instanceof Function ? function () {
+    vCallback.apply(oThis, aArgs);
+  } : vCallback, nDelay);
+};
+
+window.setInterval = function (vCallback, nDelay /*, argumentToPass1, argumentToPass2, etc. */) {
+  var oThis = this, aArgs = Array.prototype.slice.call(arguments, 2);
+  return __nativeSI__(vCallback instanceof Function ? function () {
+    vCallback.apply(oThis, aArgs);
+  } : vCallback, nDelay);
+};
+ +
These two replacements also enable the HTML5 standard passage of arbitrary arguments to the callback functions of timers in IE. So they can be used as non-standard-compliant polyfills also. See the callback arguments paragraph for a standard-compliant polyfill.
+ +

New feature test:

+ +
myArray = ['zero', 'one', 'two'];
+
+myArray.myMethod = function (sProperty) {
+    alert(arguments.length > 0 ? this[sProperty] : this);
+};
+
+setTimeout(alert, 1500, 'Hello world!'); // the standard use of setTimeout and setInterval is preserved, but...
+setTimeout.call(myArray, myArray.myMethod, 2000); // prints "zero,one,two" after 2 seconds
+setTimeout.call(myArray, myArray.myMethod, 2500, 2); // prints "two" after 2,5 seconds
+
+ +

Another, more complex, solution for the this problem is the following framework.

+ +
JavaScript 1.8.5 introduces the Function.prototype.bind() method, which lets you specify the value that should be used as this for all calls to a given function. This lets you easily bypass problems where it's unclear what this will be, depending on the context from which your function was called. Also, ES2015 supports arrow functions, with lexical this allowing us to write setInterval( () => this.myMethod) if we're inside myArray method.
+ +

MiniDaemon:一个用于管理定时器的小框架

+ +

In pages requiring many timers, it can often be difficult to keep track of all of the running timer events. One approach to solving this problem is to store information about the state of a timer in an object. Following is a minimal example of such an abstraction. The constructor architecture explicitly avoids the use of closures. It also offers an alternative way to pass the this object to the callback function (see The "this" problem for details). The following code is also available on GitHub.

+ +
For a more complex but still modular version of it (Daemon) see JavaScript Daemons Management. This more complex version is nothing but a big and scalable collection of methods for the Daemon constructor. However, the Daemon constructor itself is nothing but a clone of MiniDaemon with an added support for init and onstart functions declarable during the instantiation of the daemon. So the MiniDaemon framework remains the recommended way for simple animations, because Daemon without its collection of methods is essentially a clone of it.
+ +

minidaemon.js

+ +
+
/*\
+|*|
+|*|  :: MiniDaemon ::
+|*|
+|*|  Revision #2 - September 26, 2014
+|*|
+|*|  https://developer.mozilla.org/en-US/docs/Web/API/window.setInterval
+|*|  https://developer.mozilla.org/User:fusionchess
+|*|  https://github.com/madmurphy/minidaemon.js
+|*|
+|*|  This framework is released under the GNU Lesser General Public License, version 3 or later.
+|*|  http://www.gnu.org/licenses/lgpl-3.0.html
+|*|
+\*/
+
+function MiniDaemon (oOwner, fTask, nRate, nLen) {
+  if (!(this && this instanceof MiniDaemon)) { return; }
+  if (arguments.length < 2) { throw new TypeError('MiniDaemon - not enough arguments'); }
+  if (oOwner) { this.owner = oOwner; }
+  this.task = fTask;
+  if (isFinite(nRate) && nRate > 0) { this.rate = Math.floor(nRate); }
+  if (nLen > 0) { this.length = Math.floor(nLen); }
+}
+
+MiniDaemon.prototype.owner = null;
+MiniDaemon.prototype.task = null;
+MiniDaemon.prototype.rate = 100;
+MiniDaemon.prototype.length = Infinity;
+
+  /* These properties should be read-only */
+
+MiniDaemon.prototype.SESSION = -1;
+MiniDaemon.prototype.INDEX = 0;
+MiniDaemon.prototype.PAUSED = true;
+MiniDaemon.prototype.BACKW = true;
+
+  /* Global methods */
+
+MiniDaemon.forceCall = function (oDmn) {
+  oDmn.INDEX += oDmn.BACKW ? -1 : 1;
+  if (oDmn.task.call(oDmn.owner, oDmn.INDEX, oDmn.length, oDmn.BACKW) === false || oDmn.isAtEnd()) { oDmn.pause(); return false; }
+  return true;
+};
+
+  /* Instances methods */
+
+MiniDaemon.prototype.isAtEnd = function () {
+  return this.BACKW ? isFinite(this.length) && this.INDEX < 1 : this.INDEX + 1 > this.length;
+};
+
+MiniDaemon.prototype.synchronize = function () {
+  if (this.PAUSED) { return; }
+  clearInterval(this.SESSION);
+  this.SESSION = setInterval(MiniDaemon.forceCall, this.rate, this);
+};
+
+MiniDaemon.prototype.pause = function () {
+  clearInterval(this.SESSION);
+  this.PAUSED = true;
+};
+
+MiniDaemon.prototype.start = function (bReverse) {
+  var bBackw = Boolean(bReverse);
+  if (this.BACKW === bBackw && (this.isAtEnd() || !this.PAUSED)) { return; }
+  this.BACKW = bBackw;
+  this.PAUSED = false;
+  this.synchronize();
+};
+
+
+ +
MiniDaemon passes arguments to the callback function. If you want to work on it with browsers that natively do not support this feature, use one of the methods proposed above.
+ +

语法

+ +

var myDaemon = new MiniDaemon(thisObject, callback[, rate[, length]]);

+ +

说明

+ +

Returns a JavaScript Object containing all information needed by an animation (like the this object, the callback function, the length, the frame-rate).

+ +

参数

+ +
+
thisObject
+
The this object on which the callback function is called. It can be an object or null.
+
callback
+
The function that is repeatedly invoked . It is called with three arguments: index (the iterative index of each invocation), length (the number of total invocations assigned to the daemon - finite or Infinity) and backwards (a boolean expressing whether the index is increasing or decreasing). It is something like callback.call(thisObject, index, length, backwards). If the callback function returns a false value the daemon is paused.
+
rate (optional)
+
The time lapse (in number of milliseconds) between each invocation. The default value is 100.
+
length (optional)
+
The total number of invocations. It can be a positive integer or Infinity. The default value is Infinity.
+
+ +

MiniDaemon 实例(instance)的属性

+ +
+
myDaemon.owner
+
The this object on which is executed the daemon (read/write). It can be an object or null.
+
myDaemon.task
+
The function that is repeatedly invoked (read/write). It is called with three arguments: index (the iterative index of each invocation), length (the number of total invocations assigned to the daemon - finite or Infinity) and backwards (a boolean expressing whether the index is decreasing or not) – see above. If the myDaemon.task function returns a false value the daemon is paused.
+
myDaemon.rate
+
The time lapse (in number of milliseconds) between each invocation (read/write).
+
myDaemon.length
+
The total number of invocations. It can be a positive integer or Infinity (read/write).
+
+ +

MiniDaemon 实例的方法

+ +
+
myDaemon.isAtEnd()
+
Returns a boolean expressing whether the daemon is at the start/end position or not.
+
myDaemon.synchronize()
+
Synchronize the timer of a started daemon with the time of its invocation.
+
myDaemon.pause()
+
Pauses the daemon.
+
myDaemon.start([reverse])
+
Starts the daemon forward (index of each invocation increasing) or backwards (index decreasing).
+
+ +

MiniDaemon 全局对象的方法

+ +
+
MiniDaemon.forceCall(minidaemon)
+
Forces a single callback to the minidaemon.task function regardless of the fact that the end has been reached or not. In any case the internal INDEX property is increased/decreased (depending on the actual direction of the process).
+
+ +

使用示例

+ +

HTML:

+ +
<!DOCTYPE html>
+<html>
+<head>
+  <meta charset="UTF-8" />
+  <title>MiniDaemin Example - MDN</title>
+  <script type="text/javascript" src="minidaemon.js"></script>
+  <style type="text/css">
+    #sample_div {
+      visibility: hidden;
+    }
+  </style>
+</head>
+
+<body>
+  <p>
+    <input type="button" onclick="fadeInOut.start(false /* optional */);" value="fade in" />
+    <input type="button" onclick="fadeInOut.start(true);" value="fade out">
+    <input type="button" onclick="fadeInOut.pause();" value="pause" />
+  </p>
+
+  <div id="sample_div">Some text here</div>
+
+  <script type="text/javascript">
+    function opacity (nIndex, nLength, bBackwards) {
+      this.style.opacity = nIndex / nLength;
+      if (bBackwards ? nIndex === 0 : nIndex === 1) {
+        this.style.visibility = bBackwards ? 'hidden' : 'visible';
+      }
+    }
+
+    var fadeInOut = new MiniDaemon(document.getElementById('sample_div'), opacity, 300, 8);
+  </script>
+</body>
+</html>
+ +

View this example in action

+ +

备注

+ +

The setInterval() function is commonly used to set a delay for functions that are executed again and again, such as animations.

+ +

You can cancel the interval using {{domxref("WindowOrWorkerGlobalScope.clearInterval()")}}.

+ +

If you wish to have your function called once after the specified delay, use {{domxref("WindowOrWorkerGlobalScope.setTimeout()")}}.

+ +

Ensure that execution duration is shorter than interval frequency

+ +

If there is a possibility that your logic could take longer to execute than the interval time, it is recommended that you recursively call a named function using {{domxref("WindowOrWorkerGlobalScope.setTimeout")}}. For example, if using setInterval to poll a remote server every 5 seconds, network latency, an unresponsive server, and a host of other issues could prevent the request from completing in its allotted time. As such, you may find yourself with queued up XHR requests that won't necessarily return in order.

+ +

In these cases, a recursive setTimeout() pattern is preferred:

+ +
(function loop(){
+   setTimeout(function() {
+      // Your logic here
+
+      loop();
+  }, delay);
+})();
+
+ +

In the above snippet, a named function loop() is declared and is immediately executed. loop() is recursively called inside setTimeout() after the logic has completed executing. While this pattern does not guarantee execution on a fixed interval, it does guarantee that the previous interval has completed before recursing.

+ +

Throttling of intervals

+ +

setInterval() is subject to the same throttling restrictions in Firefox as {{domxref("WindowOrWorkerGlobalScope.setTimeout","setTimeout()")}}; see Reasons for delays longer than specified.

+ +

规范

+ + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('HTML WHATWG', 'webappapis.html#dom-setinterval', 'WindowOrWorkerGlobalScope.setInterval()')}}{{Spec2("HTML WHATWG")}}Method moved to the WindowOrWorkerGlobalScope mixin in the latest spec.
{{SpecName("HTML WHATWG", "webappapis.html#dom-setinterval", "WindowTimers.setInterval()")}}{{Spec2("HTML WHATWG")}}Initial definition (DOM Level 0)
+ +

浏览器兼容性

+ +
+ + +

{{Compat("api.WindowOrWorkerGlobalScope.setInterval")}}

+
+ +

参见

+ + diff --git a/files/zh-cn/web/api/settimeout/index.html b/files/zh-cn/web/api/settimeout/index.html new file mode 100644 index 0000000000..1499eccade --- /dev/null +++ b/files/zh-cn/web/api/settimeout/index.html @@ -0,0 +1,477 @@ +--- +title: window.setTimeout +slug: Web/API/setTimeout +tags: + - Timers + - WindowOrWorkerGlobalScope + - WindowTimers + - setTimeout +translation_of: Web/API/WindowOrWorkerGlobalScope/setTimeout +original_slug: Web/API/WindowOrWorkerGlobalScope/setTimeout +--- +

{{APIRef("HTML DOM")}}

+ +

 {{domxref("WindowOrWorkerGlobalScope")}} 混合的 setTimeout()方法设置一个定时器,该定时器在定时器到期后执行一个函数或指定的一段代码。

+ +

语法

+ +
var timeoutID = scope.setTimeout(function[, delay, arg1, arg2, ...]);
+var timeoutID = scope.setTimeout(function[, delay]);
+var timeoutID = scope.setTimeout(code[, delay]);
+ +

参数

+ +
+
function
+
{{jsxref("function")}} 是你想要在到期时间(delay毫秒)之后执行的函数
+
code
+
这是一个可选语法,你可以使用字符串而不是{{jsxref("function")}} ,在delay毫秒之后编译和执行字符串 (使用该语法是不推荐的, 原因和使用 {{jsxref("Global_Objects/eval", "eval()")}}一样,有安全风险)。
+
delay {{optional_inline}}
+
延迟的毫秒数 (一秒等于1000毫秒),函数的调用会在该延迟之后发生。如果省略该参数,delay取默认值0,意味着“马上”执行,或者尽快执行。不管是哪种情况,实际的延迟时间可能会比期待的(delay毫秒数) 值长,原因请查看{{anch("实际延时比设定值更久的原因:最小延迟时间")}}。
+
arg1, ..., argN {{optional_inline}}
+
附加参数,一旦定时器到期,它们会作为参数传递给{{jsxref("function")}} 
+
+ +
+

备注:需要注意的是,IE9 及更早的 IE 浏览器不支持向回调函数传递额外参数(第一种语法)。如果你想要在IE中达到同样的功能,你必须使用一种兼容代码 (查看  {{anch("兼容旧环境(polyfill)")}} 一段).

+
+ +

返回值

+ +

返回值timeoutID是一个正整数,表示定时器的编号。这个值可以传递给{{domxref("WindowOrWorkerGlobalScope.clearTimeout","clearTimeout()")}}来取消该定时器。

+ +

需要注意的是setTimeout()和{{domxref("WindowOrWorkerGlobalScope.setInterval", "setInterval()")}}共用一个编号池,技术上,clearTimeout()和 {{domxref("WindowOrWorkerGlobalScope.clearInterval", "clearInterval()")}} 可以互换。但是,为了避免混淆,不要混用取消定时函数。

+ +

在同一个对象上(一个window或者worker),setTimeout()或者setInterval()在后续的调用不会重用同一个定时器编号。但是不同的对象使用独立的编号池。

+ +

例子

+ +

下文的例子在网页中设置了两个简单的按钮,以触发 setTimeout() 和 clearTimeout() 方法:按下第一个按钮会设置一个定时器,定时器在 2s 后显示一个警告对话框,并将此次 setTimeout 的定时器 ID 保存起来,按下第二个按钮可以取消定时器。

+ +

HTML

+ +
<p>Live Example</p>
+<button onclick="delayedAlert();">Show an alert box after two seconds</button>
+<p></p>
+<button onclick="clearAlert();">Cancel alert before it happens</button>
+
+ +
+ +
+ +
+ +
+ +

JavaScript

+ +
var timeoutID;
+
+function delayedAlert() {
+  timeoutID = window.setTimeout(slowAlert, 2000);
+}
+
+function slowAlert() {
+  alert('That was really slow!');
+}
+
+function clearAlert() {
+  window.clearTimeout(timeoutID);
+}
+
+ +
+ +
+ +
+ +
+ +
+ +
+ +
+ +
+ +
+ +
+ +
+ +
+ +
+ +

结果展示

+ +

{{EmbedLiveSample('例子')}}

+ +

也可参考 clearTimeout() 示例.

+ +

兼容旧环境(polyfill)

+ +

如果你需要向你的回调函数内传递一个或多个参数, 而且还需要兼容那些不支持传递额外参数(不管使用setTimeout() 或者 setInterval())的浏览器时(比如,IE9及更早的版本), 你可以引入下面的兼容代码来支持向定时器函数传参。将以下代码添加到你代码的最上面:

+ +
/*\
+|*|
+|*|  Polyfill which enables the passage of arbitrary arguments to the
+|*|  callback functions of JavaScript timers (HTML5 standard syntax).
+|*|
+|*|  https://developer.mozilla.org/en-US/docs/DOM/window.setInterval
+|*|
+|*|  Syntax:
+|*|  var timeoutID = window.setTimeout(func, delay[, param1, param2, ...]);
+|*|  var timeoutID = window.setTimeout(code, delay);
+|*|  var intervalID = window.setInterval(func, delay[, param1, param2, ...]);
+|*|  var intervalID = window.setInterval(code, delay);
+|*|
+\*/
+
+(function() {
+  setTimeout(function(arg1) {
+    if (arg1 === 'test') {
+      // feature test is passed, no need for polyfill
+      return;
+    }
+    var __nativeST__ = window.setTimeout;
+    window.setTimeout = function(vCallback, nDelay /*, argumentToPass1, argumentToPass2, etc. */ ) {
+      var aArgs = Array.prototype.slice.call(arguments, 2);
+      return __nativeST__(vCallback instanceof Function ? function() {
+        vCallback.apply(null, aArgs);
+      } : vCallback, nDelay);
+    };
+  }, 0, 'test');
+
+  var interval = setInterval(function(arg1) {
+    clearInterval(interval);
+    if (arg1 === 'test') {
+      // feature test is passed, no need for polyfill
+      return;
+    }
+    var __nativeSI__ = window.setInterval;
+    window.setInterval = function(vCallback, nDelay /*, argumentToPass1, argumentToPass2, etc. */ ) {
+      var aArgs = Array.prototype.slice.call(arguments, 2);
+      return __nativeSI__(vCallback instanceof Function ? function() {
+        vCallback.apply(null, aArgs);
+      } : vCallback, nDelay);
+    };
+  }, 0, 'test');
+}())
+ +

针对IE的解决方法

+ +

如果你需要单独的针对IE9及之前浏览器的 hack 写法,你可以使用 JavaScript 条件注释:

+ +
/*@cc_on
+  // conditional IE < 9 only fix
+  @if (@_jscript_version <= 9)
+  (function(f){
+     window.setTimeout = f(window.setTimeout);
+     window.setInterval = f(window.setInterval);
+  })(function(f){return function(c,t){var a=[].slice.call(arguments,2);return f(function(){c instanceof Function?c.apply(this,a):eval(c)},t)}});
+  @end
+@*/
+ +
+ +
+ +
+ +
+ +
+ +
+ +
+ +
+ +
+ +

或者使用更加清晰的 IE HTML 条件注释:

+ +
<!--[if lte IE 9]><script>
+(function(f){
+window.setTimeout=f(window.setTimeout);
+window.setInterval=f(window.setInterval);
+})(function(f){return function(c,t){
+var a=[].slice.call(arguments,2);return f(function(){c instanceof Function?c.apply(this,a):eval(c)},t)}
+});
+</script><![endif]-->
+
+
+
+ +
+ +
+ +

变通方法

+ +

另一种方法是使用匿名函数包裹你的回调函数,这种方式要消耗更多资源:

+ +
var intervalID = setTimeout(function() { myFunc('one', 'two', 'three'); }, 1000);
+
+ +
+ +

上面那个例子也可以用箭头函数:

+ +
var intervalID = setTimeout(() => { myFunc('one', 'two', 'three'); }, 1000);
+
+ +

此外,也可使用 function's bind

+ +
setTimeout(function(arg1){}.bind(undefined, 10), 1000);
+
+ +

关于"this"的问题

+ +

当你向 setTimeout() (或者其他函数)传递一个函数时,该函数中的this指向跟你的期望可能不同,这个问题在 JavaScript reference 中进行了详细解释.

+ +

解释

+ +

setTimeout()调用的代码运行在与所在函数完全分离的执行环境上。这会导致,这些代码中包含的 this 关键字在非严格模式会指向 window (或全局)对象,严格模式下为 undefined,这和所期望的this的值是不一样的。

+ +
+

备注:即使是在严格模式下,setTimeout()的回调函数里面的this仍然默认指向window对象, 并不是undefined

+
+ +

查看下面的例子:

+ +
let myArray = ["zero", "one", "two"];
+myArray.myMethod = function (sProperty) {
+    alert(arguments.length > 0 ? this[sProperty] : this);
+};
+
+myArray.myMethod(); // prints "zero,one,two"
+myArray.myMethod(1); // prints "one"
+ +

上面这段代码正常工作,用myArray调用,在函数内,this[sProperty]等于 myArray[sProperty]。然后,下面这个例子:

+ +
setTimeout(myArray.myMethod, 1000); // prints "[object Window]" after 1 second
+setTimeout(myArray.myMethod, 1500, "1"); // prints "undefined" after 1.5 seconds
+ +

myArray.myMethod函数传递给 setTimeout,到了定时时间,this没有指向,默认指向window对象。并且没有方法把 thisArg 传递给setTimeout,正如Array方法的forEachreduce等。下面的例子表示使用call方法设置this也没用。

+ +
setTimeout.call(myArray, myArray.myMethod, 2000); // error: "NS_ERROR_XPC_BAD_OP_ON_WN_PROTO: Illegal operation on WrappedNative prototype object"
+setTimeout.call(myArray, myArray.myMethod, 2500, 2); // same error
+ +

可能的解决方案

+ +

一个通用的方法是用包装函数来设置this

+ +
setTimeout(function(){myArray.myMethod()}, 2000); // prints "zero,one,two" after 2 seconds
+setTimeout(function(){myArray.myMethod('1')}, 2500); // prints "one" after 2.5 seconds
+ +

箭头函数也可以:

+ +
setTimeout(() => {myArray.myMethod()}, 2000); // prints "zero,one,two" after 2 seconds
+setTimeout(() => {myArray.myMethod('1')}, 2500); // prints "one" after 2.5 seconds
+ +

另一个解决this问题的方法是使用两个非原生的 setTimeout()setInterval() 全局函数代替原生的。该非原生的函数通过使用Function.prototype.call 方法激活了正确的作用域。下面的代码显示了应该如何替换:

+ +
// Enable the passage of the 'this' object through the JavaScript timers
+
+var __nativeST__ = window.setTimeout, __nativeSI__ = window.setInterval;
+
+window.setTimeout = function (vCallback, nDelay /*, argumentToPass1, argumentToPass2, etc. */) {
+  var oThis = this, aArgs = Array.prototype.slice.call(arguments, 2);
+  return __nativeST__(vCallback instanceof Function ? function () {
+    vCallback.apply(oThis, aArgs);
+  } : vCallback, nDelay);
+};
+
+window.setInterval = function (vCallback, nDelay /*, argumentToPass1, argumentToPass2, etc. */) {
+  var oThis = this, aArgs = Array.prototype.slice.call(arguments, 2);
+  return __nativeSI__(vCallback instanceof Function ? function () {
+    vCallback.apply(oThis, aArgs);
+  } : vCallback, nDelay);
+};
+ +
备注: 这两个替换也让 IE支持了符合 HTML5 标准的定时器函数。所以也能作为一个 polyfills。查看 Callback arguments 一段.
+ +

新特性检测:

+ +
let myArray = ["zero", "one", "two"];
+myArray.myMethod = function (sProperty) {
+    alert(arguments.length > 0 ? this[sProperty] : this);
+};
+
+setTimeout(alert, 1500, "Hello world!"); // the standard use of setTimeout and setInterval is preserved, but...
+setTimeout.call(myArray, myArray.myMethod, 2000); // prints "zero,one,two" after 2 seconds
+setTimeout.call(myArray, myArray.myMethod, 2500, 2); // prints "two" after 2,5 seconds
+
+ +

针对这个问题并没有原生的解决方案。

+ +
注:JavaScript 1.8.5 引入了 Function.prototype.bind() 方法,该方法允许显式地指定函数调用时 this 所指向的值 。该方法可以帮助你解决 this 指向不确定的问题。
+ +

使用bind()的例子:

+ +
let myArray = ['zero', 'one', 'two'];
+myBoundMethod = (function (sProperty) {
+    console.log(arguments.length > 0 ? this[sProperty] : this);
+}).bind(myArray);
+
+myBoundMethod(); // prints "zero,one,two" because 'this' is bound to myArray in the function
+myBoundMethod(1); // prints "one"
+setTimeout(myBoundMethod, 1000); // still prints "zero,one,two" after 1 second because of the binding
+setTimeout(myBoundMethod, 1500, "1"); // prints "one" after 1.5 seconds
+
+ +

备注

+ +

你可以使用 {{domxref("WindowOrWorkerGlobalScope.clearTimeout()","clearTimeout()")}}来取消定时器。

+ +

如果你希望你的代码被重复的调用 (比如每 N 毫秒一次),考虑使用{{domxref("WindowOrWorkerGlobalScope.setInterval()","setInterval()")}}。

+ +

传递字符串字面量

+ +

setTimeout()传递一个字符串而不是函数会遭受到与使用eval一样的风险.

+ +
// 推荐
+window.setTimeout(function() {
+    alert("Hello World!");
+}, 500);
+
+// 不推荐
+window.setTimeout("alert(\"Hello World!\");", 500);
+
+
+ +

字符串会在全局作用域内被解释执行,所以当setTimeout()函数执行完毕后,字符串中的变量不可用.

+ +

实际延时比设定值更久的原因:最小延迟时间

+ +

有很多因素会导致setTimeout的回调函数执行比设定的预期值更久,本节将讨论最常见的原因。

+ +

最小延时 >=4ms

+ +

在浏览器中,setTimeout()/{{domxref("WindowOrworkerGlobalScope.setInterval","setInterval()")}} 的每调用一次定时器的最小间隔是4ms,这通常是由于函数嵌套导致(嵌套层级达到一定深度),或者是由于已经执行的setInterval的回调函数阻塞导致的。例如:

+ +
function cb() { f(); setTimeout(cb, 0); }
+setTimeout(cb, 0);
+ +
setInterval(f, 0);
+ +

在Chrome 和 Firefox中, 定时器的第5次调用被阻塞了;在Safari是在第6次;Edge是在第3次。Gecko 从这个版本 version 56开始对 setInterval() 开始采用这样的机制(setTimeout()已经实现,具体请参考以下内容)。

+ +

一直以来,不同浏览器中出现这种最小延迟的情况有所不同(例如Firefox) - 从其他地方调用了setInterval( ),或者在嵌套函数调用setTimeout( ) 时(嵌套级别达到特定深度时),都会出现超时延迟。

+ +

如果想在浏览器中实现0ms延时的定时器,你可以参考这里所说的{domxref("window.postMessage()")}}

+ +
+

Note: 最小延时, DOM_MIN_TIMEOUT_VALUE, 是4ms  (但在Firefox中通常是是存储在 dom.min_timeout_value 这个变量中), DOM_CLAMP_TIMEOUT_NESTING_LEVEL 的第5层.

+
+ +
+

Note: 4 ms 是在  HTML5 spec  中精确的,并且在2010年及以后的跨浏览器中保持了一致,这个数值比 {{geckoRelease("5.0")}}规定的嵌套函数的最小延时10ms更为精确。

+
+ +

未被激活的tabs的定时最小延迟>=1000ms

+ +

为了优化后台tab的加载损耗(以及降低耗电量),在未被激活的tab中定时器的最小延时限制为1S(1000ms)。

+ +

Firefox 从version 5 (see {{bug(633421)}}开始采取这种机制,1000ms的间隔值可以通过 dom.min_background_timeout_value 改变。Chrome 从 version 11 (crbug.com/66078)开始采用。

+ +

Android 版的Firefox对未被激活的后台tabs的使用了15min的最小延迟间隔时间 ,并且这些tabs也能完全不被加载。

+ +
+

当 Web Audio API {{domxref("AudioContext")}} 正在被用来播放音频的时候,Firefox 50不会再限制后台tabs的加载。 后续的Firefox 51 版本修正了这个问题,即使在没有音频播放的情况下,也不再限制后台tabs的加载。这个解决了一些软件应用在后台tabs中播放基于文本的音频( note-based) 时,无法去同步音频和画面的问题。

+
+ +

追踪型脚本的最小延时限制

+ +

从Firefox 55版本开始,追踪型脚本(例如 谷歌分析,或者其他的一些被Firefox 的 TP lists 识别为追踪型脚本的 外链URL脚本)是重点限制加载的对象。在当前正在使用的页面中,这个节流限制的延时依然是4ms。但是在后台tabs中,这个最小延时限制是10000ms(10s),这个限制会在文档第一次加载后的30s后生效。

+ +

控制这些行为的属性包含以下这些:

+ + + +

超时延迟

+ +

除了"最小延时"之外,定时器仍然有可能因为当前页面(或者操作系统/浏览器本身)被其他任务占用导致延时。 需要被强调是, 直到调用 setTimeout()的主线程执行完其他任务之后,回调函数和代码段才能被执行。例如:

+ +
function foo() {
+  console.log('foo has been called');
+}
+setTimeout(foo, 0);
+console.log('After setTimeout');
+ +

会在控制台输出:

+ +
After setTimeout
+foo has been called
+ +

出现这个结果的原因是,尽管setTimeout 以0ms的延迟来调用函数,但这个任务已经被放入了队列中并且等待下一次执行;并不是立即执行;队列中的等待函数被调用之前,当前代码必须全部运行完毕,因此这里运行结果并非预想的那样。

+ +

WebExtension Background pages和定时器

+ +

在 WebExtension 中 background pages,timers工作不正常。这主要因为background pages实际上,并不是一次性全部加载:如果浏览器没有使用它,就不加载,如果需要就恢复。这对于WebExtension是透明的,但是有些事件(包括JS的timers)不会在不加载/恢复循环中执行,所以WebExtension中建议使用alarms。更详细的细节在合并到事件驱动后台脚本

+ +

在本文写作的时候,只有Chrome展示了如上的特性 — Firefox没有未加载/恢复循环的行为,所以timers仍然可以工作。但是,仍然建议不要在WebExtension中使用timers:

+ +

1.兼容Chorme。

+ +

2.未来行为的改变会引起问题。

+ +

最大延时值

+ +

包括 IE,  Chrome, Safari, Firefox 在内的浏览器其内部以32位带符号整数存储延时。这就会导致如果一个延时(delay)大于 2147483647 毫秒 (大约24.8 天)时就会溢出,导致定时器将会被立即执行。

+ +

规范

+ + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('HTML WHATWG', 'webappapis.html#dom-settimeout', 'WindowOrWorkerGlobalScope.setTimeout()')}}{{Spec2("HTML WHATWG")}}Method moved to the WindowOrWorkerGlobalScope mixin in the latest spec.
{{SpecName("HTML WHATWG", "webappapis.html#dom-settimeout", "WindowTimers.setTimeout()")}}{{Spec2("HTML WHATWG")}}Initial definition (DOM Level 0)
+ +

浏览器兼容性

+ +
+ + +

{{Compat("api.WindowOrWorkerGlobalScope.setTimeout")}}

+
+ +

相关链接:

+ + diff --git a/files/zh-cn/web/api/windoworworkerglobalscope/atob/index.html b/files/zh-cn/web/api/windoworworkerglobalscope/atob/index.html deleted file mode 100644 index f664a3908e..0000000000 --- a/files/zh-cn/web/api/windoworworkerglobalscope/atob/index.html +++ /dev/null @@ -1,75 +0,0 @@ ---- -title: WindowOrWorkerGlobalScope.atob() -slug: Web/API/WindowOrWorkerGlobalScope/atob -tags: - - API - - Base64 - - DOM - - WindowOrWorkerGlobalScope - - atob - - 参考 - - 方法 -translation_of: Web/API/WindowOrWorkerGlobalScope/atob -original_slug: Web/API/WindowBase64/atob ---- -

{{APIRef("HTML DOM")}}

- -

WindowOrWorkerGlobalScope.atob() 对经过 base-64 编码的字符串进行解码。你可以使用 {{domxref("WindowBase64.btoa","window.btoa()")}} 方法来编码一个可能在传输过程中出现问题的数据,并且在接受数据之后,使用 atob() 方法再将数据解码。例如:你可以编码、传输和解码操作各种字符,比如 0-31 的 ASCII 码值。

- -

关于针对 Unicode 或者 UTF-8 的应用方面,请查看 this note at Base64 encoding and decodingbtoa() 的备注

- -

语法

- -
var decodedData = scope.atob(encodedData);
- -

异常

- -

如果传入字符串不是有效的 base64 字符串,比如其长度不是 4 的倍数,则抛出{{jsxref("DOMException")}}。

- -

示例

- -
let encodedData = window.btoa("Hello, world"); // 编码
-let decodedData = window.atob(encodedData);    // 解码
-
- -

规范

- - - - - - - - - - - - - - - - - - - - - - - - - - -
SpecificationStatusComment
{{SpecName('HTML WHATWG', '#dom-windowbase64-atob', 'WindowBase64.atob()')}}{{Spec2('HTML WHATWG')}}No change since the latest snapshot, {{SpecName("HTML5.1")}}.
{{SpecName('HTML5.1', '#dom-windowbase64-atob', 'WindowBase64.atob()')}}{{Spec2('HTML5.1')}}Snapshot of {{SpecName("HTML WHATWG")}}. No change.
{{SpecName("HTML5 W3C", "#dom-windowbase64-atob", "WindowBase64.atob()")}}{{Spec2('HTML5 W3C')}}Snapshot of {{SpecName("HTML WHATWG")}}. Creation of WindowBase64 (properties were on the target before it).
- -

浏览器兼容性

- -

{{Compat("api.WindowOrWorkerGlobalScope.atob")}}

- -

参见

- - diff --git a/files/zh-cn/web/api/windoworworkerglobalscope/btoa/index.html b/files/zh-cn/web/api/windoworworkerglobalscope/btoa/index.html deleted file mode 100644 index 83873fc559..0000000000 --- a/files/zh-cn/web/api/windoworworkerglobalscope/btoa/index.html +++ /dev/null @@ -1,172 +0,0 @@ ---- -title: WindowOrWorkerGlobalScope.btoa() -slug: Web/API/WindowOrWorkerGlobalScope/btoa -tags: - - API - - Base64 - - Web - - WindowOrWorkerGlobalScope - - 参考 - - 字符串 - - 数据 - - 方法 -translation_of: Web/API/WindowOrWorkerGlobalScope/btoa -original_slug: Web/API/WindowBase64/btoa ---- -

{{APIRef("HTML DOM")}}

- -

WindowOrWorkerGlobalScope.btoa() 从 {{jsxref("String")}} 对象中创建一个 base-64 编码的 ASCII 字符串,其中字符串中的每个字符都被视为一个二进制数据字节。

- -
-

Note: 由于这个函数将每个字符视为二进制数据的字节,而不管实际组成字符的字节数是多少,所以如果任何字符的{{Glossary("code point", "码位")}}超出 0x00 ~ 0xFF 这个范围,则会引发 InvalidCharacterError 异常。请参阅 {{anch("Unicode_字符串")}} ,该示例演示如何编码含有码位超出 0x00 ~ 0xFF 范围的字符的字符串。

-
- -

语法

- -
let encodedData = window.btoa(stringToEncode);
-
- -

参数

- -
-
stringToEncode
-
一个字符串, 其字符分别表示要编码为 ASCII 的二进制数据的单个字节。
-
- -

返回值

- -

一个包含 stringToEncode 的 Base64 表示的字符串。

- -

示例

- -
let encodedData = window.btoa("Hello, world"); // 编码
-let decodedData = window.atob(encodedData);    // 解码
-
- -

备注

- -

你可以使用此方法对可能导致通信问题的数据进行编码,传输,然后使用 {{domxref("WindowOrWorkerGlobalScope.atob","atob()")}} 方法再次解码数据。例如,可以编码控制字符,包括 ASCII 值为 0 到 31 的字符。

- -

在用 JavaScript 编写 XPCOM 组件时,btoa() 方法也是可用的,虽然全局对象已经不是 {{domxref("Window")}} 了。

- -

Unicode 字符串

- -

在多数浏览器中,使用 btoa() 对 Unicode 字符串进行编码都会触发 InvalidCharacterError 异常。

- -

一种选择是转义任何扩展字符,以便实际编码的字符串是原始字符的 ASCII 表示形式。考虑这个例子,代码来自 Johan Sundström

- -
// ucs-2 string to base64 encoded ascii
-function utoa(str) {
-    return window.btoa(unescape(encodeURIComponent(str)));
-}
-// base64 encoded ascii to ucs-2 string
-function atou(str) {
-    return decodeURIComponent(escape(window.atob(str)));
-}
-// Usage:
-utoa('✓ à la mode'); // 4pyTIMOgIGxhIG1vZGU=
-atou('4pyTIMOgIGxhIG1vZGU='); // "✓ à la mode"
-
-utoa('I \u2661 Unicode!'); // SSDimaEgVW5pY29kZSE=
-atou('SSDimaEgVW5pY29kZSE='); // "I ♡ Unicode!"
-
- -

更好、更可靠、性能更优异的解决方案是使用类型化数组进行转换。

- -

规范

- - - - - - - - - - - - - - - - - - - - - - - - - - -
规范状态备注
{{SpecName('HTML WHATWG', '#dom-btoa', 'WindowOrWorkerGlobalScope.btoa()')}}{{Spec2('HTML WHATWG')}}Method moved to the WindowOrWorkerGlobalScope mixin in the latest spec.
{{SpecName('HTML5.1', '#dom-windowbase64-btoa', 'WindowBase64.btoa()')}}{{Spec2('HTML5.1')}}Snapshot of {{SpecName("HTML WHATWG")}}. No change.
{{SpecName("HTML5 W3C", "#dom-windowbase64-btoa", "WindowBase64.btoa()")}}{{Spec2('HTML5 W3C')}}Snapshot of {{SpecName("HTML WHATWG")}}. Creation of WindowBase64 (properties where on the target before it).
- -

Polyfill

- -
// Polyfill from  https://github.com/MaxArt2501/base64-js/blob/master/base64.js
-(function() {
-    // base64 character set, plus padding character (=)
-    var b64 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",
-
-        // Regular expression to check formal correctness of base64 encoded strings
-        b64re = /^(?:[A-Za-z\d+\/]{4})*?(?:[A-Za-z\d+\/]{2}(?:==)?|[A-Za-z\d+\/]{3}=?)?$/;
-
-    window.btoa = window.btoa || function(string) {
-        string = String(string);
-        var bitmap, a, b, c,
-            result = "",
-            i = 0,
-            rest = string.length % 3; // To determine the final padding
-
-        for (; i < string.length;) {
-            if ((a = string.charCodeAt(i++)) > 255 ||
-                (b = string.charCodeAt(i++)) > 255 ||
-                (c = string.charCodeAt(i++)) > 255)
-                throw new TypeError("Failed to execute 'btoa' on 'Window': The string to be encoded contains characters outside of the Latin1 range.");
-
-            bitmap = (a << 16) | (b << 8) | c;
-            result += b64.charAt(bitmap >> 18 & 63) + b64.charAt(bitmap >> 12 & 63) +
-                b64.charAt(bitmap >> 6 & 63) + b64.charAt(bitmap & 63);
-        }
-
-        // If there's need of padding, replace the last 'A's with equal signs
-        return rest ? result.slice(0, rest - 3) + "===".substring(rest) : result;
-    };
-
-    window.atob = window.atob || function(string) {
-        // atob can work with strings with whitespaces, even inside the encoded part,
-        // but only \t, \n, \f, \r and ' ', which can be stripped.
-        string = String(string).replace(/[\t\n\f\r ]+/g, "");
-        if (!b64re.test(string))
-            throw new TypeError("Failed to execute 'atob' on 'Window': The string to be decoded is not correctly encoded.");
-
-        // Adding the padding if missing, for semplicity
-        string += "==".slice(2 - (string.length & 3));
-        var bitmap, result = "",
-            r1, r2, i = 0;
-        for (; i < string.length;) {
-            bitmap = b64.indexOf(string.charAt(i++)) << 18 | b64.indexOf(string.charAt(i++)) << 12 |
-                (r1 = b64.indexOf(string.charAt(i++))) << 6 | (r2 = b64.indexOf(string.charAt(i++)));
-
-            result += r1 === 64 ? String.fromCharCode(bitmap >> 16 & 255) :
-                r2 === 64 ? String.fromCharCode(bitmap >> 16 & 255, bitmap >> 8 & 255) :
-                String.fromCharCode(bitmap >> 16 & 255, bitmap >> 8 & 255, bitmap & 255);
-        }
-        return result;
-    };
-})()
-
- -

浏览器兼容性

- -

{{Compat("api.WindowOrWorkerGlobalScope.btoa")}}

- -

参见

- - diff --git a/files/zh-cn/web/api/windoworworkerglobalscope/caches/index.html b/files/zh-cn/web/api/windoworworkerglobalscope/caches/index.html deleted file mode 100644 index 8debcc3322..0000000000 --- a/files/zh-cn/web/api/windoworworkerglobalscope/caches/index.html +++ /dev/null @@ -1,127 +0,0 @@ ---- -title: WindowOrWorkerGlobalScope.caches -slug: Web/API/WindowOrWorkerGlobalScope/caches -translation_of: Web/API/WindowOrWorkerGlobalScope/caches ---- -

{{APIRef()}}{{SeeCompatTable}}

- -

caches 是{{domxref("WindowOrWorkerGlobalScope")}}接口的一个只读属性,它返回了与当前上下文紧密相关的{{domxref("CacheStorage")}}对象。此对象激活了诸如存储用于离线使用的资产,并生成对请求生成自定义响应等功能。

- -

语法

- -
var myCacheStorage = self.caches; // or just caches
-
- -

- -

{{domxref("CacheStorage")}} 对象.

- -

例子

- -

下面的例子展示了你在service worker上下文中如何应该运用cache对离线资产的进行存储。

- -
this.addEventListener('install', function(event) {
-  event.waitUntil(
-    caches.open('v1').then(function(cache) {
-      return cache.addAll(
-        '/sw-test/',
-        '/sw-test/index.html',
-        '/sw-test/style.css',
-        '/sw-test/app.js',
-        '/sw-test/image-list.js',
-        '/sw-test/star-wars-logo.jpg',
-        '/sw-test/gallery/',
-        '/sw-test/gallery/bountyHunters.jpg',
-        '/sw-test/gallery/myLittleVader.jpg',
-        '/sw-test/gallery/snowTroopers.jpg'
-      );
-    })
-  );
-});
- -

规范

- - - - - - - - - - - - - - - - - - - -
SpecificationStatusComment
{{SpecName('Service Workers', '#self-caches', 'caches')}}{{Spec2('Service Workers')}}Defined in a WindowOrWorkerGlobalScope partial in the newest spec.
{{SpecName('Service Workers')}}{{Spec2('Service Workers')}}Initial definition.
- -

Browser compatibility

- -

{{CompatibilityTable}}

- -
- - - - - - - - - - - - - - - - - - - -
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support40.0{{CompatGeckoDesktop(42)}}
- {{CompatGeckoDesktop(52)}}[1]
{{CompatNo}}{{CompatUnknown}}{{CompatNo}}
-
- -
- - - - - - - - - - - - - - - - - - - - - -
FeatureAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatGeckoMobile(42)}}
- {{CompatGeckoMobile(52)}}[1]
{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
-
- -

[1] caches 现在被定义在 {{domxref("WindowOrWorkerGlobalScope")}} 中的mixin里.

- -

相关链接

- - diff --git a/files/zh-cn/web/api/windoworworkerglobalscope/clearinterval/index.html b/files/zh-cn/web/api/windoworworkerglobalscope/clearinterval/index.html deleted file mode 100644 index 442e1bb81e..0000000000 --- a/files/zh-cn/web/api/windoworworkerglobalscope/clearinterval/index.html +++ /dev/null @@ -1,75 +0,0 @@ ---- -title: WindowTimers.clearInterval() -slug: Web/API/WindowOrWorkerGlobalScope/clearInterval -tags: - - API - - WindowOrWorkerGlobalScope - - 参考 - - 方法 -translation_of: Web/API/WindowOrWorkerGlobalScope/clearInterval -original_slug: Web/API/Window/clearInterval ---- -
{{ApiRef("HTML DOM")}}
- -

{{domxref("WindowOrWorkerGlobalScope")}} mixin 的 clearInterval() 方法可取消先前通过 {{domxref("WindowOrWorkerGlobalScope.setInterval", "setInterval()")}} 设置的重复定时任务。

- -

语法

- -
scope.clearInterval(intervalID)
-
- -

Parameters

- -
-
intervalID
-
要取消的定时器的 ID。是由 setInterval() 返回的。
-
- -

值得一提的是,{{domxref("WindowOrWorkerGlobalScope.setInterval", "setInterval()")}} 和 {{domxref("WindowOrWorkerGlobalScope.setTimeout", "setTimeout()")}} 共用其定义的 IDs,即可以使用 clearInterval() 和 {{domxref("WindowOrWorkerGlobalScope.clearTimeout", "clearTimeout()")}} 中的任意一个。然而,为了使代码可读性更强,你应该尽量避免这种用法。

- -

返回值

- -

{{jsxref("undefined")}}

- -

示例

- -

查看 setInterval() 的示例

- -

规范

- - - - - - - - - - - - - - - - - - - -
规范状态备注
{{SpecName('HTML WHATWG', 'webappapis.html#dom-clearinterval', 'WindowOrWorkerGlobalScope.clearInterval()')}}{{Spec2("HTML WHATWG")}}Method moved to the WindowOrWorkerGlobalScope mixin in the latest spec.
{{SpecName('HTML WHATWG', 'webappapis.html#dom-clearinterval', 'clearInterval()')}}{{Spec2('HTML WHATWG')}}
- -

浏览器兼容性

- - - -

{{Compat("api.WindowOrWorkerGlobalScope.clearInterval")}}

- -

参见

- - diff --git a/files/zh-cn/web/api/windoworworkerglobalscope/cleartimeout/index.html b/files/zh-cn/web/api/windoworworkerglobalscope/cleartimeout/index.html deleted file mode 100644 index 4e700ea7d0..0000000000 --- a/files/zh-cn/web/api/windoworworkerglobalscope/cleartimeout/index.html +++ /dev/null @@ -1,151 +0,0 @@ ---- -title: WindowOrWorkerGlobalScope.clearTimeout() -slug: Web/API/WindowOrWorkerGlobalScope/clearTimeout -tags: - - API - - WindowOrWorkerGlobalScope - - clearTimeout -translation_of: Web/API/WindowOrWorkerGlobalScope/clearTimeout -original_slug: Web/API/WindowTimers/clearTimeout ---- -
-
{{APIRef("HTML DOM")}}
-
- -

{{domxref("WindowOrWorkerGlobalScope")}}内置的clearTimeout()方法取消了先前通过调用{{domxref("WindowOrWorkerGlobalScope.setTimeout", "setTimeout()")}}建立的定时器。

- -

语法

- -
scope.clearTimeout(timeoutID)
- - - -

Parameters

- -
-
timeoutID
-
您要取消定时器的标识符。 该ID由相应的setTimeout()调用返回。
-
- -

值得注意的是,{{domxref("WindowOrWorkerGlobalScope.setTimeout", "setTimeout()")}}和{{domxref("WindowOrWorkerGlobalScope.setInterval", "setInterval()")}}使用共享的ID池, 意味着在技术上可以混用clearTimeout()和{{domxref("WindowOrWorkerGlobalScope.clearInterval", "clearInterval()")}} 。 但是,为了清楚起见,你应该避免这样做。

- -

示例

- -

在一个网页中运行如下脚本,并且点击一次页面。一秒钟后你会看见弹出一条信息。如果你在一秒内不停点击页面,弹出框将不再出现。

- -
var alarm = {
-  remind: function(aMessage) {
-    alert(aMessage);
-    delete this.timeoutID;
-  },
-
-  setup: function() {
-    this.cancel();
-    var self = this;
-    this.timeoutID = window.setTimeout(function(msg) {self.remind(msg);}, 1000, "Wake up!");
-  },
-
-  cancel: function() {
-    if(typeof this.timeoutID == "number") {
-      window.clearTimeout(this.timeoutID);
-      delete this.timeoutID;
-    }
-  }
-};
-window.onclick = function() { alarm.setup() };
- -

注意

- -

传入一个错误的 ID 给 clearTimeout()不会有任何影响;也不会抛出异常。

- -

规范

- - - - - - - - - - - - - - - - - - - -
SpecificationStatusComment
{{SpecName('HTML WHATWG', 'webappapis.html#dom-cleartimeout', 'WindowOrWorkerGlobalScope.clearTimeout()')}}{{Spec2("HTML WHATWG")}}Method moved to the WindowOrWorkerGlobalScope mixin in the latest spec.
{{SpecName('HTML WHATWG', 'webappapis.html#dom-cleartimeout', 'clearTimeout()')}}{{Spec2('HTML WHATWG')}}
- -

浏览器兼容

- -

{{CompatibilityTable}}

- -
- - - - - - - - - - - - - - - - - - - - - -
FeatureChromeEdgeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support1.0{{CompatVersionUnknown}}{{CompatGeckoDesktop("1")}}
- {{CompatGeckoDesktop("52")}}[1]
4.04.01.0
-
- -
- - - - - - - - - - - - - - - - - - - - - - - -
FeatureAndroidChrome for AndroidEdgeFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support1.01.0{{CompatVersionUnknown}}{{CompatGeckoMobile("1")}}
- {{CompatGeckoMobile("52")}}[1]
6.06.01.0
-
- -

[1] clearTimeout() now defined on {{domxref("WindowOrWorkerGlobalScope")}} mixin.

- -

更多

- - diff --git a/files/zh-cn/web/api/windoworworkerglobalscope/createimagebitmap/index.html b/files/zh-cn/web/api/windoworworkerglobalscope/createimagebitmap/index.html deleted file mode 100644 index 7d55152960..0000000000 --- a/files/zh-cn/web/api/windoworworkerglobalscope/createimagebitmap/index.html +++ /dev/null @@ -1,207 +0,0 @@ ---- -title: self.createImageBitmap() -slug: Web/API/WindowOrWorkerGlobalScope/createImageBitmap -translation_of: Web/API/WindowOrWorkerGlobalScope/createImageBitmap ---- -
{{APIRef("Canvas API")}}
- -

createImageBitmap 方法存在 windows 和 workers 中. 它接受各种不同的图像来源, 并返回一个{{domxref("Promise")}}, resolve为{{domxref("ImageBitmap")}}. 可选地参数,图像被剪裁成自(sx,sy)且宽度为sw,高度为sh的像素的矩形。

- -

Syntax

- -
createImageBitmap(image[, options]).then(function(response) { ... });
-createImageBitmap(image, sx, sy, sw, sh[, options]).then(function(response) { ... });
-
- -

Parameters

- -
-
image
-
一个图像源, 可以是一个 {{HTMLElement("img")}}, SVG {{SVGElement("image")}}, {{HTMLElement("video")}}, {{HTMLElement("canvas")}}, {{domxref("HTMLImageElement")}}, {{domxref("SVGImageElement")}}, {{domxref("HTMLVideoElement")}}, {{domxref("HTMLCanvasElement")}}, {{domxref("Blob")}}, {{domxref("ImageData")}}, {{domxref("ImageBitmap")}}, 或 {{domxref("OffscreenCanvas")}} 对象.
-
sx
-
裁剪点x坐标.
-
sy
-
裁剪点y坐标.
-
sw
-
裁剪宽度,值可为负数.
-
sh
-
裁剪高度,值可为负数.
-
options {{optional_inline}}
-
为其设置选项的对象。可用的选项是: -
    -
  • imageOrientation: 指示图像是按原样呈现还是垂直翻转.  none (默认不翻转) 或 flipY.
  • -
  • premultiplyAlpha: 指示位图颜色通道由alpha通道预乘. 选择其一:none, premultiply, 或 default (默认).
  • -
  • colorSpaceConversion: 指示图像是否使用色彩空间转换进行解码. none 或 default (默认). The value default indicates that implementation-specific behavior is used.
  • -
  • resizeWidth: 指示新宽度的长整数。
  • -
  • resizeHeight: 指示新高度的长整数。
  • -
  • resizeQuality: 指定图像缩放算法. 选择其一pixelated, low (默认), medium, 或 high.
  • -
-
-
- -

Return value

- -

返回一个解决ImageBitmap的{{domxref("Promise")}} ,当Promise成功时resolves接收一个包含所得到的矩形的位图数据{{domxref("ImageBitmap")}}。

- -

Example

- -
var canvas = document.getElementById('myCanvas'),
-ctx = canvas.getContext('2d'),
-image = new Image();
-
-image.onload = function() {
-  Promise.all([
-    createImageBitmap(this, 0, 0, 32, 32),
-    createImageBitmap(this, 32, 0, 32, 32)
-  ]).then(function(sprites) {
-    ctx.drawImage(sprites[0], 0, 0);
-    ctx.drawImage(sprites[1], 32, 32);
-  });
-}
-
-image.src = 'sprites.png';
-
- -

Specifications

- - - - - - - - - - - - - - -
SpecificationStatusComment
{{SpecName('HTML WHATWG', "webappapis.html#dom-createimagebitmap", "createImageBitmap")}}{{Spec2('HTML WHATWG')}} 
- -

Browser compatibility

- -

{{ CompatibilityTable}}

- -
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
FeatureChromeFirefox (Gecko)EdgeInternet ExplorerOperaSafari
Basic support{{CompatChrome(50)}} -

{{CompatGeckoDesktop(42)}}
- {{CompatGeckoDesktop(52)}}[1]

-
{{CompatNo}}{{CompatNo}}{{CompatVersionUnknown}}{{CompatNo}}
options parameter{{CompatChrome(52)}}{{CompatUnknown}}{{CompatNo}}{{CompatNo}}39{{CompatNo}}
resizeWidth, resizeHeight, and resizeQuality{{CompatChrome(54)}}{{CompatUnknown}}{{CompatNo}}{{CompatNo}}{{CompatUnknown}}{{CompatNo}}
SVGImageElement as source image{{CompatChrome(59)}}{{CompatUnknown}}{{CompatNo}}{{CompatNo}}{{CompatUnknown}}{{CompatNo}}
-
- -
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
FeatureAndroid WebviewChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{CompatChrome(50)}}{{CompatChrome(50)}} -

{{CompatGeckomobile(42)}}
- {{CompatGeckoMobile(52)}}[1]

-
{{CompatUnknown}}{{CompatVersionUnknown}}{{CompatUnknown}}
options parameter{{CompatChrome(52)}}{{CompatChrome(52)}}{{CompatUnknown}}{{CompatUnknown}}39{{CompatUnknown}}
resizeWidth, resizeHeight, and resizeQuality{{CompatChrome(54)}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}} 
SVGImageElement as source image{{CompatChrome(59)}}{{CompatChrome(59)}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
-
- -

[1] createImageBitmap() now defined on {{domxref("WindowOrWorkerGlobalScope")}} mixin.

- -

See also

- - - -

- -

diff --git a/files/zh-cn/web/api/windoworworkerglobalscope/crossoriginisolated/index.html b/files/zh-cn/web/api/windoworworkerglobalscope/crossoriginisolated/index.html deleted file mode 100644 index ad19e53c2e..0000000000 --- a/files/zh-cn/web/api/windoworworkerglobalscope/crossoriginisolated/index.html +++ /dev/null @@ -1,58 +0,0 @@ ---- -title: WindowOrWorkerGlobalScope.crossOriginIsolated -slug: Web/API/WindowOrWorkerGlobalScope/crossOriginIsolated -translation_of: Web/API/WindowOrWorkerGlobalScope/crossOriginIsolated ---- -
{{APIRef()}}{{SeeCompatTable}}
- -

crossOriginIsolated 是 {{domxref("WindowOrWorkerGlobalScope")}} 的一个只读属性,返回一个布尔值,该值指示是否可以通过{{domxref("Window.postMessage()")}}调用发送 {{jsxref("SharedArrayBuffer")}}。

- -

该值取决于响应中存在的{{httpheader("Cross-Origin-Opener-Policy")}} 和{{httpheader("Cross-Origin-Embedder-Policy")}} 头。

- -

语法

- -
var myCrossOriginIsolated = self.crossOriginIsolated; // 或直接 crossOriginIsolated
-
- -

类型

- -

布尔类型

- -

示例

- -
if(crossOriginIsolated) {
-  // post SharedArrayBuffer
-} else {
-  // Do something else
-}
-
- -

规范

- - - - - - - - - - - - - - -
SpecificationStatusComment
{{SpecName("HTML WHATWG")}}Not yet merged into the spec
- -

浏览器兼容性

- - - -

{{Compat("api.WindowOrWorkerGlobalScope.crossOriginIsolated")}}

- -

参见

- - diff --git a/files/zh-cn/web/api/windoworworkerglobalscope/fetch/index.html b/files/zh-cn/web/api/windoworworkerglobalscope/fetch/index.html deleted file mode 100644 index 3ebf7d8fdb..0000000000 --- a/files/zh-cn/web/api/windoworworkerglobalscope/fetch/index.html +++ /dev/null @@ -1,173 +0,0 @@ ---- -title: WorkerOrGlobalScope.fetch() -slug: Web/API/WindowOrWorkerGlobalScope/fetch -tags: - - API - - Experimental - - Fetch - - FetchAPI - - GlobalFetch - - request -translation_of: Web/API/WindowOrWorkerGlobalScope/fetch ---- -

{{APIRef("Fetch")}}

- -

位于 {{domxref("WorkerOrGlobalScope")}} 这一个 mixin 中的 fetch() 方法用于发起获取资源的请求。它返回一个 promise,这个 promise 会在请求响应后被 resolve,并传回 {{domxref("Response")}} 对象。

- -

{{domxref("Window")}} 和 {{domxref("WorkerGlobalScope")}} 都实现了 WorkerOrGlobalScope。 ——这意味着基本在任何场景下只要你想获取资源,都可以使用 位于 WorkerOrGlobalScope 中的 fetch() 方法。

- -

当遇到网络错误时,{{domxref("WorkerOrGlobalScope.fetch","fetch()")}} 返回的 promise 会被 reject,并传回 {{jsxref("TypeError")}},虽然这也可能因为权限或其它问题导致。成功的 fetch() 检查不仅要包括 promise 被 resolve,还要包括 {{domxref("Response.ok")}} 属性为 true。HTTP 404 状态并不被认为是网络错误。

- -

fetch() 方法由 Content Security Policy 的 connect-src指令控制,而不是它请求的资源。

- -
-

注意:{{domxref("WorkerOrGlobalScope.fetch","fetch()")}} 方法的参数与 {{domxref("Request.Request","Request()")}} 构造器是一样的。

-
- -

语法

- -
Promise<Response> fetch(input[, init]);
-
- -

参数

- -
-
?input
-
定义要获取的资源。这可能是: -
    -
  • 一个 {{domxref("USVString")}} 字符串,包含要获取资源的 URL。一些浏览器会接受 blob: 和 data: 作为 schemes.
  • -
  • 一个 {{domxref("Request")}} 对象。
  • -
-
-
init {{optional_inline}}
-
一个配置项对象,包括所有对请求的设置。可选的参数有: -
    -
  • method: 请求使用的方法,如 GETPOST。
  • -
  • headers: 请求的头信息,形式为 {{domxref("Headers")}} 的对象或包含 {{domxref("ByteString")}} 值的对象字面量。
  • -
  • body: 请求的 body 信息:可能是一个 {{domxref("Blob")}}、{{domxref("BufferSource")}}、{{domxref("FormData")}}、{{domxref("URLSearchParams")}} 或者 {{domxref("USVString")}} 对象。注意 GET 或 HEAD 方法的请求不能包含 body 信息。
  • -
  • mode: 请求的模式,如 cors、 no-cors 或者 same-origin。
  • -
  • credentials: 请求的 credentials,如 omitsame-origin 或者 include。为了在当前域名内自动发送 cookie , 必须提供这个选项, 从 Chrome 50 开始, 这个属性也可以接受 {{domxref("FederatedCredential")}} 实例或是一个 {{domxref("PasswordCredential")}} 实例。
  • -
  • cache:  请求的 cache 模式: default、 no-storereload 、 no-cache 、 force-cache 或者 only-if-cached
  • -
  • redirect: 可用的 redirect 模式: follow (自动重定向), error (如果产生重定向将自动终止并且抛出一个错误), 或者 manual (手动处理重定向). 在Chrome中默认使用follow(Chrome 47之前的默认值是manual)。
  • -
  • referrer: 一个 {{domxref("USVString")}} 可以是 no-referrerclient或一个 URL。默认是 client。
  • -
  • referrerPolicy: 指定了HTTP头部referer字段的值。可能为以下值之一: no-referrer、 no-referrer-when-downgrade、 origin、 origin-when-cross-origin、 unsafe-url 。
  • -
  • integrity: 包括请求的  subresource integrity 值 ( 例如: sha256-BpfBw7ivV8q2jLiT13fxDYAe2tJllusRSZ273h2nFSE=)。
  • -
-
-
- -

返回值

- -

一个 {{jsxref("Promise")}},resolve 时回传 {{domxref("Response")}} 对象。

- -

例外

- - - - - - - - - - - - - - - - - - -
类型描述
AbortError请求被{{domxref("AbortController.abort()")}}终止。
TypeErrorFirefox 43开始,如果fetch()接收到含有用户名和密码的URL(例如http://user:password@example.com),它将会抛出一个TypeError
- -

示例

- -

Fetch Request 示例 (参见 Fetch Request live) 中,我们使用对应的构造器创建了一个新的 {{domxref("Request")}} 对象,然后调用 fetch() 方法获取资源。因为我们是在请求一个图片,为了解析正常,我们对响应执行 {{domxref("Body.blob")}} 来设置相应的 MIME 类型。然后创建一个 Object URL,并在 {{htmlelement("img")}} 元素中把它显示出来。

- -
var myImage = document.querySelector('img');
-
-var myRequest = new Request('flowers.jpg');
-
-fetch(myRequest).then(function(response) {
-  return response.blob();
-}).then(function(response) {
-  var objectURL = URL.createObjectURL(response);
-  myImage.src = objectURL;
-});
- -

在 Fetch with init then Request 示例 (参见 Fetch Request init live) 中,我们做同样的操作,除了在调用 fetch() 时传入一个 init 对象:

- -
var myImage = document.querySelector('img');
-
-var myHeaders = new Headers();
-myHeaders.append('Content-Type', 'image/jpeg');
-
-var myInit = { method: 'GET',
-               headers: myHeaders,
-               mode: 'cors',
-               cache: 'default' };
-
-var myRequest = new Request('flowers.jpg');
-
-fetch(myRequest,myInit).then(function(response) {
-  ...
-});
- -

你也可以传入同样的 init 对象到 Request 构造器,来实现同样的效果,如:

- -
var myRequest = new Request('flowers.jpg',myInit);
-
- -

init 对象中的 headers 也可以是一个对象字面量:

- -
var myInit = { method: 'GET',
-               headers: {
-                   'Content-Type': 'image/jpeg'
-               },
-               mode: 'cors',
-               cache: 'default' };
-
-var myRequest = new Request('flowers.jpg', myInit);
- -

规范

- - - - - - - - - - - - - - - - - - - - - - - - -
SpecificationStatusComment
{{SpecName('Fetch','#fetch-method','fetch()')}}{{Spec2('Fetch')}}Defined in a WindowOrWorkerGlobalScope partial in the newest spec.
{{SpecName('Fetch','#dom-global-fetch','fetch()')}}{{Spec2('Fetch')}}Initial definition
{{SpecName('Credential Management')}}{{Spec2('Credential Management')}}Adds {{domxref("FederatedCredential")}} or {{domxref("PasswordCredential")}} instance as a possible value for init.credentials.
- -

浏览器兼容性

- - - -

{{Compat("api.WindowOrWorkerGlobalScope.fetch")}}

- -

相关链接

- - diff --git a/files/zh-cn/web/api/windoworworkerglobalscope/indexeddb/index.html b/files/zh-cn/web/api/windoworworkerglobalscope/indexeddb/index.html deleted file mode 100644 index 1c1f17f52c..0000000000 --- a/files/zh-cn/web/api/windoworworkerglobalscope/indexeddb/index.html +++ /dev/null @@ -1,175 +0,0 @@ ---- -title: WindowOrWorkerGlobalScope.indexedDB -slug: Web/API/WindowOrWorkerGlobalScope/indexedDB -tags: - - API - - Database - - IndexedDB - - Reference - - Storage - - WindowOrWorkerGlobalScope - - 参考 - - 属性 -translation_of: Web/API/WindowOrWorkerGlobalScope/indexedDB ---- -

{{ APIRef() }}

- -

indexedDB 是 {{domxref("WindowOrWorkerGlobalScope")}}的一个只读属性,它集成了为应用程序提供异步访问索引数据库的功能的机制。.

- -

语法

- -
var IDBFactory = self.indexedDB;
- -
-

-
- -

一个 {{domxref("IDBFactory")}} 对象.

- -

示例

- -
var db;
-function openDB() {
- var DBOpenRequest = window.indexedDB.open('toDoList');
- DBOpenRequest.onsuccess = function(e) {
-   db = DBOpenRequest.result;
- }
-}
- -

规范

- - - - - - - - - - - - - - - - - - - -
SpecificationStatusComment
{{SpecName('IndexedDB 2', '#dom-windoworworkerglobalscope-indexeddb', 'indexedDB')}}{{Spec2('IndexedDB 2')}}Defined in a WindowOrWorkerGlobalScope partial in the newest spec.
{{SpecName('IndexedDB', '#widl-IDBEnvironment-indexedDB', 'indexedDB')}}{{Spec2('IndexedDB')}}Initial definition.
- -

浏览器兼容性

- -
{{CompatibilityTable}}
- -
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
FeatureChromeEdgeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Basic support23{{property_prefix("webkit")}}
- 24
{{CompatVersionUnknown}}10 {{property_prefix("moz")}}
- {{CompatGeckoDesktop("16.0")}}
- {{CompatGeckoDesktop("52.0")}}[1]
10, partial157.1
Available in workers{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatGeckoMobile("37.0")}}{{CompatUnknown}}{{CompatVersionUnknown}}{{CompatUnknown}}
Indexed Database 2.0{{CompatChrome(58)}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatOpera(45)}}{{CompatUnknown}}
-
- -
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
FeatureAndroid WebviewChrome for AndroidEdgeFirefox Mobile (Gecko)Firefox OSIE PhoneOpera MobileSafari Mobile
Basic support{{CompatVersionUnknown}}{{CompatUnknown}}{{CompatVersionUnknown}}{{CompatGeckoMobile("22.0")}}
- {{CompatGeckoMobile("52.0")}}[1]
1.0.110228
Available in workers{{CompatVersionUnknown}}{{CompatUnknown}}{{CompatVersionUnknown}}{{CompatGeckoMobile("37.0")}}{{CompatVersionUnknown}}{{CompatUnknown}}{{CompatVersionUnknown}}{{CompatUnknown}}
Indexed Database 2.0{{CompatChrome(58)}}{{CompatChrome(58)}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatOperaMobile(45)}}{{CompatUnknown}}
-
- -

[1] indexedDB 定义在 {{domxref("WindowOrWorkerGlobalScope")}} mixin(一种实现多继承的方法)上.

- -

相关链接

- - diff --git a/files/zh-cn/web/api/windoworworkerglobalscope/issecurecontext/index.html b/files/zh-cn/web/api/windoworworkerglobalscope/issecurecontext/index.html deleted file mode 100644 index d9f72b13a5..0000000000 --- a/files/zh-cn/web/api/windoworworkerglobalscope/issecurecontext/index.html +++ /dev/null @@ -1,100 +0,0 @@ ---- -title: WindowOrWorkerGlobalScope.isSecureContext -slug: Web/API/WindowOrWorkerGlobalScope/isSecureContext -tags: - - API - - Property - - Reference - - Window - - WindowOrWorkerGlobalContext - - Workers - - isSecureContext -translation_of: Web/API/WindowOrWorkerGlobalScope/isSecureContext ---- -

{{APIRef()}}{{SeeCompatTable}}

- -

isSecureContext 是 {{domxref("WindowOrWorkerGlobalScope")}} 的一个只读属性,返回一个布尔值,标识当前上下文是否安全,安全(true)或不安全(false)。

- -

语法

- -
var isItSecure = self.isSecureContext; // 或者直接使用 isSecureContext
-
- -

类型

- -

 {{domxref("Boolean")}}.

- -

规范

- - - - - - - - - - - - - - -
SpecificationStatusComment
{{SpecName('Secure Contexts', 'webappapis.html#dom-origin', 'WindowOrWorkerGlobalScope.isSecureContext')}}{{Spec2('Secure Contexts')}}Initial definition.
- -

浏览器兼容性

- -

{{CompatibilityTable}}

- -
- - - - - - - - - - - - - - - - - - - -
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support{{CompatChrome(55)}}{{CompatGeckoDesktop(52)}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
-
- -
- - - - - - - - - - - - - - - - - - - - - -
FeatureAndroid WebviewChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{CompatChrome(55)}}{{CompatChrome(55)}}{{CompatGeckoMobile(52)}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
-
- -

参考

- - diff --git a/files/zh-cn/web/api/windoworworkerglobalscope/origin/index.html b/files/zh-cn/web/api/windoworworkerglobalscope/origin/index.html deleted file mode 100644 index eac425fbd9..0000000000 --- a/files/zh-cn/web/api/windoworworkerglobalscope/origin/index.html +++ /dev/null @@ -1,98 +0,0 @@ ---- -title: WindowOrWorkerGlobalScope.origin -slug: Web/API/WindowOrWorkerGlobalScope/origin -tags: - - global scope - - origin - - serialized -translation_of: Web/API/WindowOrWorkerGlobalScope/origin ---- -

{{APIRef()}}{{SeeCompatTable}}{{domxref("WindowOrWorkerGlobalScope")}} 接口的 origin 只读属性返回全局范围的 origin, 序列化为一个字符串。

- -

Syntax

- -
let myOrigin = self.origin; // or just origin
-
- -

Value

- -

A {{domxref("USVString")}}.

- -

Examples

- -

Executed from inside a worker script, the following snippet will log the worker's global scope's origin to the console each time it receives a message

- -
onmessage = function() {
-  console.log(self.origin);
-};
- -

If the origin is not a scheme/host/port tuple (say you are trying to run it locally, i.e. via file:// URL), origin will return the string "null".

- -

Specifications

- - - - - - - - - - - - - - -
SpecificationStatusComment
{{SpecName('HTML WHATWG', 'webappapis.html#dom-origin', 'WindowOrWorkerGlobalScope.origin')}}{{Spec2('HTML WHATWG')}}Initial definition.
- -

Browser compatibility

- -

{{CompatibilityTable}}

- -
- - - - - - - - - - - - - - - - - - - -
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support{{CompatChrome(59)}}{{CompatGeckoDesktop(54)}}{{CompatNo}}{{CompatNo}}{{CompatNo}}
-
- -
- - - - - - - - - - - - - - - - - - - - - -
FeatureAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{CompatChrome(59)}}{{CompatChrome(59)}}{{CompatGeckoMobile(54)}} {{CompatNo}}{{CompatNo}}{{CompatNo}}
-
diff --git a/files/zh-cn/web/api/windoworworkerglobalscope/queuemicrotask/index.html b/files/zh-cn/web/api/windoworworkerglobalscope/queuemicrotask/index.html deleted file mode 100644 index 3f81e04235..0000000000 --- a/files/zh-cn/web/api/windoworworkerglobalscope/queuemicrotask/index.html +++ /dev/null @@ -1,108 +0,0 @@ ---- -title: WindowOrWorkerGlobalScope.queueMicrotask() -slug: Web/API/WindowOrWorkerGlobalScope/queueMicrotask -tags: - - API - - JavaScript - - Method - - Microtask - - 参考 - - 同步 - - 方法 -translation_of: Web/API/WindowOrWorkerGlobalScope/queueMicrotask ---- -
{{APIRef("HTML DOM")}}
- -
{{domxref("Window")}} 或 {{domxref("Worker")}} 接口的 queueMicrotask() 方法,queues a microtask to be executed at a safe time prior to control returning to the browser's event loop.microtask 是一个简短的函数,它将在当前任务(task)完成其工作之后运行,并且在执行上下文的控制返回到浏览器的事件循环之前,没有其他代码等待运行。The microtask is a short function which will run after the current task has completed its work and when there is no other code waiting to be run before control of the execution context is returned to the browser's event loop.
- -
- -

This lets your code run without interfering with any other, potentially higher priority, code that is pending, but before the browser regains control over the execution context, potentially depending on work you need to complete. You can learn more about how to use microtasks and why you might choose to do so in our microtask guide.

- -

The importance of microtasks comes in its ability to perform tasks asynchronously but in a specific order. See Using microtasks in JavaScript with queueMicrotask() for more details.

- -

Microtasks are especially useful for libraries and frameworks that need to perform final cleanup or other just-before-rendering tasks.

- -

queueMicrotask() 处于 {{domxref("WindowOrWorkerGlobalScope")}} mixin 之下。

- -

语法

- -
scope.queueMicrotask(function);
-
- -

参数

- -
-
function
-
A {{jsxref("function")}} to be executed when the browser engine determines it is safe to call your code.微任务(microtask)的执行顺序在所有挂起的任务(pending tasks)完成之后,在对浏览器的事件循环产生控制(yielding control to the browser's event loop)之前。
-
- -

返回值

- -

undefined

- -

示例

- -
self.queueMicrotask(() => {
-  // 函数的内容
-})
- -

来自 queueMicrotask 的规范文档:

- -
MyElement.prototype.loadData = function (url) {
-  if (this._cache[url]) {
-    queueMicrotask(() => {
-      this._setData(this._cache[url]);
-      this.dispatchEvent(new Event("load"));
-    });
-  } else {
-    fetch(url).then(res => res.arrayBuffer()).then(data => {
-      this._cache[url] = data;
-      this._setData(data);
-      this.dispatchEvent(new Event("load"));
-    });
-  }
-};
- -

polyfill

- -

下面的代码是一份 queueMicrotask() 的 polyfill。它通过使用立即 resolve 的 promise 创建一个微任务(microtask),如果无法创建 promise,则回落(fallback)到使用setTimeout()

- -
if (typeof window.queueMicrotask !== "function") {
-  window.queueMicrotask = function (callback) {
-    Promise.resolve()
-      .then(callback)
-      .catch(e => setTimeout(() => { throw e; }));
-  };
-}
-
- -

规范

- - - - - - - - - - - - - - -
SpecificationStatusComment
{{SpecName("HTML WHATWG", "timers-and-user-prompts.html#microtask-queuing", "self.queueMicrotask()")}}{{Spec2("HTML WHATWG")}}Initial definition
- -

浏览器兼容性

- -

{{Compat("api.WindowOrWorkerGlobalScope.queueMicrotask")}}

- -

参见

- - diff --git a/files/zh-cn/web/api/windoworworkerglobalscope/setinterval/index.html b/files/zh-cn/web/api/windoworworkerglobalscope/setinterval/index.html deleted file mode 100644 index d5a453b133..0000000000 --- a/files/zh-cn/web/api/windoworworkerglobalscope/setinterval/index.html +++ /dev/null @@ -1,636 +0,0 @@ ---- -title: window.setInterval -slug: Web/API/WindowOrWorkerGlobalScope/setInterval -tags: - - API - - DOM - - 定时 - - 方法 - - 时间 -translation_of: Web/API/WindowOrWorkerGlobalScope/setInterval -original_slug: Web/API/Window/setInterval ---- -
{{ ApiRef("HTML DOM") }}
- -

{{domxref("WindowOrWorkerGlobalScope")}} 的 setInterval() 方法重复调用一个函数或执行一个代码段,在每次调用之间具有固定的时间延迟。

- -

在窗口和工作接口上提供的setInterval()方法重复调用函数或执行代码片段,每次调用之间有固定的时间延迟。它返回一个时间间隔ID,该ID唯一地标识时间间隔,因此您可以稍后通过调用clearInterval()来删除它。这个方法是由WindowOrWorkerGlobalScope mixin定义的。

- -

语法

- -
var intervalID = scope.setInterval(func, delay, [arg1, arg2, ...]);
-var intervalID = scope.setInterval(code, delay);
-
- -

参数

- -
-
func
-
要重复调用的函数。 每经过指定 延迟 毫秒后执行的{{jsxref("函数")}} 。该函数不接受任何参数,也没有返回值。
-
code
-
这个语法是可选的,你可以传递一个字符串来代替一个函数对象,你传递的字符串会被编译然后每个delay毫秒时间内执行一次。这个语法因为存在安全风险所以不被推荐使用。
-
delay
-
是每次延迟的毫秒数 (一秒等于1000毫秒),函数的每次调用会在该延迟之后发生。和setTimeout一样,实际的延迟时间可能会稍长一点。这个时间计算单位是毫秒(千分之一秒),这个定时器会使指定方法或者代码段执行的时候进行时间延迟。如果这个参数值小于10,则默认使用值为10。请注意,真正延迟时间或许更长; 请参考示例: {{SectionOnPage("/en-US/docs/Web/API/WindowOrWorkerGlobalScope/setTimeout", "Reasons for delays longer than specified")}} 
-
arg1, ..., argN {{optional_inline}}
-
当定时器过期的时候,将被传递给func指定函数的附加参数。
-
- -

返回值

- -

此返回值intervalID是一个非零数值,用来标识通过setInterval()创建的计时器,这个值可以用来作为clearInterval()的参数来清除对应的计时器 。

- -

值得注意的是,setInterval()setTimeout()共享同一个ID池,并且clearInterval()clearTimeout()在技术上是可互换使用的。但是,我们必须去匹配clearInterval()clearTimeout()对应的id,以避免代码杂乱无章,增强代码的可维护性。

- -
Note: The delay argument is converted to a signed 32-bit integer. This effectively limits delay to 2147483647 ms, since it's specified as a signed integer in the IDL.
- -

示例

- -

例1:基本用法

- -

下面例子是 setInterval()的基本语法

- -
var intervalID = window.setInterval(myCallback, 500, 'Parameter 1', 'Parameter 2');
-
-function myCallback(a, b)
-{
- // Your code here
- // Parameters are purely optional.
- console.log(a);
- console.log(b);
-}
-
- -

例2:两种颜色的切换

- -

下面的例子里会每隔一秒就调用函数 flashtext() 一次,直至你通过按下 Stop 按钮来清除本次重复操作的唯一辨识符 intervalID

- -
<!DOCTYPE html>
-<html>
-<head>
-  <meta charset="UTF-8" />
-  <title>setInterval/clearInterval example</title>
-
-  <script>
-    var nIntervId;
-
-    function changeColor() {
-      nIntervId = setInterval(flashText, 1000);
-    }
-
-    function flashText() {
-      var oElem = document.getElementById('my_box');
-      oElem.style.color = oElem.style.color == 'red' ? 'blue' : 'red';
-      // oElem.style.color == 'red' ? 'blue' : 'red' is a ternary operator.
-    }
-
-    function stopTextColor() {
-      clearInterval(nIntervId);
-    }
-  </script>
-</head>
-
-<body onload="changeColor();">
-  <div id="my_box">
-    <p>Hello World</p>
-  </div>
-
-  <button onclick="stopTextColor();">Stop</button>
-</body>
-</html>
-
- -

例3:打字机效果

- -

下面这个例子通过键入、删除和再次键入所有 NodeList 中的符合特定的选择器的字符,以达到打字机的效果。

- -
-
<!DOCTYPE html>
-<html>
-<head>
-<meta charset="UTF-8" />
-<title>JavaScript Typewriter - MDN Example</title>
-<script>
-function Typewriter (sSelector, nRate) {
-
-  function clean () {
-    clearInterval(nIntervId);
-    bTyping = false;
-    bStart = true;
-    oCurrent = null;
-    aSheets.length = nIdx = 0;
-  }
-
-  function scroll (oSheet, nPos, bEraseAndStop) {
-    if (!oSheet.hasOwnProperty("parts") || aMap.length < nPos) { return true; }
-
-    var oRel, bExit = false;
-
-    if (aMap.length === nPos) { aMap.push(0); }
-
-    while (aMap[nPos] < oSheet.parts.length) {
-      oRel = oSheet.parts[aMap[nPos]];
-
-      scroll(oRel, nPos + 1, bEraseAndStop) ? aMap[nPos]++ : bExit = true;
-
-      if (bEraseAndStop && (oRel.ref.nodeType - 1 | 1) === 3 && oRel.ref.nodeValue) {
-        bExit = true;
-        oCurrent = oRel.ref;
-        sPart = oCurrent.nodeValue;
-        oCurrent.nodeValue = "";
-      }
-
-      oSheet.ref.appendChild(oRel.ref);
-      if (bExit) { return false; }
-    }
-
-    aMap.length--;
-    return true;
-  }
-
-  function typewrite () {
-    if (sPart.length === 0 && scroll(aSheets[nIdx], 0, true) && nIdx++ === aSheets.length - 1) { clean(); return; }
-
-    oCurrent.nodeValue += sPart.charAt(0);
-    sPart = sPart.slice(1);
-  }
-
-  function Sheet (oNode) {
-    this.ref = oNode;
-    if (!oNode.hasChildNodes()) { return; }
-    this.parts = Array.prototype.slice.call(oNode.childNodes);
-
-    for (var nChild = 0; nChild < this.parts.length; nChild++) {
-      oNode.removeChild(this.parts[nChild]);
-      this.parts[nChild] = new Sheet(this.parts[nChild]);
-    }
-  }
-
-  var
-    nIntervId, oCurrent = null, bTyping = false, bStart = true,
-    nIdx = 0, sPart = "", aSheets = [], aMap = [];
-
-  this.rate = nRate || 100;
-
-  this.play = function () {
-    if (bTyping) { return; }
-    if (bStart) {
-      var aItems = document.querySelectorAll(sSelector);
-
-      if (aItems.length === 0) { return; }
-      for (var nItem = 0; nItem < aItems.length; nItem++) {
-        aSheets.push(new Sheet(aItems[nItem]));
-        /* Uncomment the following line if you have previously hidden your elements via CSS: */
-        // aItems[nItem].style.visibility = "visible";
-      }
-
-      bStart = false;
-    }
-
-    nIntervId = setInterval(typewrite, this.rate);
-    bTyping = true;
-  };
-
-  this.pause = function () {
-    clearInterval(nIntervId);
-    bTyping = false;
-  };
-
-  this.terminate = function () {
-    oCurrent.nodeValue += sPart;
-    sPart = "";
-    for (nIdx; nIdx < aSheets.length; scroll(aSheets[nIdx++], 0, false));
-    clean();
-  };
-}
-
-/* usage: */
-var oTWExample1 = new Typewriter(/* elements: */ "#article, h1, #info, #copyleft", /* frame rate (optional): */ 15);
-
-/* default frame rate is 100: */
-var oTWExample2 = new Typewriter("#controls");
-
-/* you can also change the frame rate value modifying the "rate" property; for example: */
-// oTWExample2.rate = 150;
-
-onload = function () {
-  oTWExample1.play();
-  oTWExample2.play();
-};
-</script>
-<style type="text/css">
-span.intLink, a, a:visited {
-  cursor: pointer;
-  color: #000000;
-  text-decoration: underline;
-}
-
-#info {
-  width: 180px;
-  height: 150px;
-  float: right;
-  background-color: #eeeeff;
-  padding: 4px;
-  overflow: auto;
-  font-size: 12px;
-  margin: 4px;
-  border-radius: 5px;
-  /* visibility: hidden; */
-}
-</style>
-</head>
-
-<body>
-
-<p id="copyleft" style="font-style: italic; font-size: 12px; text-align: center;">CopyLeft 2012 by <a href="https://developer.mozilla.org/" target="_blank">Mozilla Developer Network</a></p>
-<p id="controls" style="text-align: center;">[&nbsp;<span class="intLink" onclick="oTWExample1.play();">Play</span> | <span class="intLink" onclick="oTWExample1.pause();">Pause</span> | <span class="intLink" onclick="oTWExample1.terminate();">Terminate</span>&nbsp;]</p>
-<div id="info">
-Vivamus blandit massa ut metus mattis in fringilla lectus imperdiet. Proin ac ante a felis ornare vehicula. Fusce pellentesque lacus vitae eros convallis ut mollis magna pellentesque. Pellentesque placerat enim at lacus ultricies vitae facilisis nisi fringilla. In tincidunt tincidunt tincidunt.
-</div>
-<h1>JavaScript Typewriter</h1>
-
-<div id="article">
-<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nullam ultrices dolor ac dolor imperdiet ullamcorper. Suspendisse quam libero, luctus auctor mollis sed, malesuada condimentum magna. Quisque in ante tellus, in placerat est. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Donec a mi magna, quis mattis dolor. Etiam sit amet ligula quis urna auctor imperdiet nec faucibus ante. Mauris vel consectetur dolor. Nunc eget elit eget velit pulvinar fringilla consectetur aliquam purus. Curabitur convallis, justo posuere porta egestas, velit erat ornare tortor, non viverra justo diam eget arcu. Phasellus adipiscing fermentum nibh ac commodo. Nam turpis nunc, suscipit a hendrerit vitae, volutpat non ipsum.</p>
-<form>
-<p>Phasellus ac nisl lorem: <input type="text" /><br />
-<textarea style="width: 400px; height: 200px;">Nullam commodo suscipit lacus non aliquet. Phasellus ac nisl lorem, sed facilisis ligula. Nam cursus lobortis placerat. Sed dui nisi, elementum eu sodales ac, placerat sit amet mauris. Pellentesque dapibus tellus ut ipsum aliquam eu auctor dui vehicula. Quisque ultrices laoreet erat, at ultrices tortor sodales non. Sed venenatis luctus magna, ultricies ultricies nunc fringilla eget. Praesent scelerisque urna vitae nibh tristique varius consequat neque luctus. Integer ornare, erat a porta tempus, velit justo fermentum elit, a fermentum metus nisi eu ipsum. Vivamus eget augue vel dui viverra adipiscing congue ut massa. Praesent vitae eros erat, pulvinar laoreet magna. Maecenas vestibulum mollis nunc in posuere. Pellentesque sit amet metus a turpis lobortis tempor eu vel tortor. Cras sodales eleifend interdum.</textarea></p>
-<input type="submit" value="Send" />
-</form>
-<p>Duis lobortis sapien quis nisl luctus porttitor. In tempor semper libero, eu tincidunt dolor eleifend sit amet. Ut nec velit in dolor tincidunt rhoncus non non diam. Morbi auctor ornare orci, non euismod felis gravida nec. Curabitur elementum nisi a eros rutrum nec blandit diam placerat. Aenean tincidunt risus ut nisi consectetur cursus. Ut vitae quam elit. Donec dignissim est in quam tempor consequat. Aliquam aliquam diam non felis convallis suscipit. Nulla facilisi. Donec lacus risus, dignissim et fringilla et, egestas vel eros. Duis malesuada accumsan dui, at fringilla mauris bibStartum quis. Cras adipiscing ultricies fermentum. Praesent bibStartum condimentum feugiat.</p>
-<p>Nam faucibus, ligula eu fringilla pulvinar, lectus tellus iaculis nunc, vitae scelerisque metus leo non metus. Proin mattis lobortis lobortis. Quisque accumsan faucibus erat, vel varius tortor ultricies ac. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed nec libero nunc. Nullam tortor nunc, elementum a consectetur et, ultrices eu orci. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Pellentesque a nisl eu sem vehicula egestas.</p>
-</div>
-</body>
-</html>
-
- -

查看示例效果,亦可参考:clearInterval()

- -

回调参数

- -

如前所述,Internet Explorer 9及以下版本不支持在setTimeout()setInterval()中向回调函数传递参数。下面的IE专用代码演示了一种克服这种限制的方法。使用时,只需将以下代码添加到你的脚本顶部即可。

- -
/*\
-|*|
-|*|  IE-specific polyfill that enables the passage of arbitrary arguments to the
-|*|  callback functions of javascript timers (HTML5 standard syntax).
-|*|
-|*|  https://developer.mozilla.org/en-US/docs/Web/API/window.setInterval
-|*|  https://developer.mozilla.org/User:fusionchess
-|*|
-|*|  Syntax:
-|*|  var timeoutID = window.setTimeout(func, delay[, arg1, arg2, ...]);
-|*|  var timeoutID = window.setTimeout(code, delay);
-|*|  var intervalID = window.setInterval(func, delay[, arg1, arg2, ...]);
-|*|  var intervalID = window.setInterval(code, delay);
-|*|
-\*/
-
-if (document.all && !window.setTimeout.isPolyfill) {
-  var __nativeST__ = window.setTimeout;
-  window.setTimeout = function (vCallback, nDelay /*, argumentToPass1, argumentToPass2, etc. */) {
-    var aArgs = Array.prototype.slice.call(arguments, 2);
-    return __nativeST__(vCallback instanceof Function ? function () {
-      vCallback.apply(null, aArgs);
-    } : vCallback, nDelay);
-  };
-  window.setTimeout.isPolyfill = true;
-}
-
-if (document.all && !window.setInterval.isPolyfill) {
-  var __nativeSI__ = window.setInterval;
-  window.setInterval = function (vCallback, nDelay /*, argumentToPass1, argumentToPass2, etc. */) {
-    var aArgs = Array.prototype.slice.call(arguments, 2);
-    return __nativeSI__(vCallback instanceof Function ? function () {
-      vCallback.apply(null, aArgs);
-    } : vCallback, nDelay);
-  };
-  window.setInterval.isPolyfill = true;
-}
-
- -

另一种方式是使用匿名函数调用你的回调函数,但是这种方式开销较大。例如:

- -
var intervalID = setInterval(function() { myFunc('one', 'two', 'three'); }, 1000);
- -

还有一种方式是使用 function's bind. 例如:

- -
var intervalID = setInterval(function(arg1) {}.bind(undefined, 10), 1000);
- -

{{h3_gecko_minversion("Inactive tabs", "5.0")}}

- -

Starting in Gecko 5.0 {{geckoRelease("5.0")}}, intervals are clamped to fire no more often than once per second in inactive tabs.

- -

"this" 的问题

- -

当你给 setInterval() 传递一个方法或者函数的时候,this 值的绑定会存在一些问题。  这个问题在JavaScript 参考 进行了详细解释。

- -

解释

- -

Code executed by setInterval() runs in a separate execution context than the function from which it was called. As a consequence, the this keyword for the called function is set to the window (or global) object, it is not the same as the this value for the function that called setTimeout. See the following example (which uses setTimeout() instead of setInterval() – the problem, in fact, is the same for both timers):

- -
myArray = ['zero', 'one', 'two'];
-
-myArray.myMethod = function (sProperty) {
-    alert(arguments.length > 0 ? this[sProperty] : this);
-};
-
-myArray.myMethod(); // prints "zero,one,two"
-myArray.myMethod(1); // prints "one"
-setTimeout(myArray.myMethod, 1000); // prints "[object Window]" after 1 second
-setTimeout(myArray.myMethod, 1500, "1"); // prints "undefined" after 1,5 seconds
-// passing the 'this' object with .call won't work
-// because this will change the value of this inside setTimeout itself
-// while we want to change the value of this inside myArray.myMethod
-// in fact, it will be an error because setTimeout code expects this to be the window object:
-setTimeout.call(myArray, myArray.myMethod, 2000); // error: "NS_ERROR_XPC_BAD_OP_ON_WN_PROTO: Illegal operation on WrappedNative prototype object"
-setTimeout.call(myArray, myArray.myMethod, 2500, 2); // same error
-
- -

As you can see there are no ways to pass the this object to the callback function in the legacy JavaScript.

- -

一个可能的解决方案

- -

A possible way to solve the "this" problem is to replace the two native setTimeout() or setInterval() global functions with two non-native ones that enable their invocation through the Function.prototype.call method. The following example shows a possible replacement:

- -
// Enable the passage of the 'this' object through the JavaScript timers
-
-var __nativeST__ = window.setTimeout, __nativeSI__ = window.setInterval;
-
-window.setTimeout = function (vCallback, nDelay /*, argumentToPass1, argumentToPass2, etc. */) {
-  var oThis = this, aArgs = Array.prototype.slice.call(arguments, 2);
-  return __nativeST__(vCallback instanceof Function ? function () {
-    vCallback.apply(oThis, aArgs);
-  } : vCallback, nDelay);
-};
-
-window.setInterval = function (vCallback, nDelay /*, argumentToPass1, argumentToPass2, etc. */) {
-  var oThis = this, aArgs = Array.prototype.slice.call(arguments, 2);
-  return __nativeSI__(vCallback instanceof Function ? function () {
-    vCallback.apply(oThis, aArgs);
-  } : vCallback, nDelay);
-};
- -
These two replacements also enable the HTML5 standard passage of arbitrary arguments to the callback functions of timers in IE. So they can be used as non-standard-compliant polyfills also. See the callback arguments paragraph for a standard-compliant polyfill.
- -

New feature test:

- -
myArray = ['zero', 'one', 'two'];
-
-myArray.myMethod = function (sProperty) {
-    alert(arguments.length > 0 ? this[sProperty] : this);
-};
-
-setTimeout(alert, 1500, 'Hello world!'); // the standard use of setTimeout and setInterval is preserved, but...
-setTimeout.call(myArray, myArray.myMethod, 2000); // prints "zero,one,two" after 2 seconds
-setTimeout.call(myArray, myArray.myMethod, 2500, 2); // prints "two" after 2,5 seconds
-
- -

Another, more complex, solution for the this problem is the following framework.

- -
JavaScript 1.8.5 introduces the Function.prototype.bind() method, which lets you specify the value that should be used as this for all calls to a given function. This lets you easily bypass problems where it's unclear what this will be, depending on the context from which your function was called. Also, ES2015 supports arrow functions, with lexical this allowing us to write setInterval( () => this.myMethod) if we're inside myArray method.
- -

MiniDaemon:一个用于管理定时器的小框架

- -

In pages requiring many timers, it can often be difficult to keep track of all of the running timer events. One approach to solving this problem is to store information about the state of a timer in an object. Following is a minimal example of such an abstraction. The constructor architecture explicitly avoids the use of closures. It also offers an alternative way to pass the this object to the callback function (see The "this" problem for details). The following code is also available on GitHub.

- -
For a more complex but still modular version of it (Daemon) see JavaScript Daemons Management. This more complex version is nothing but a big and scalable collection of methods for the Daemon constructor. However, the Daemon constructor itself is nothing but a clone of MiniDaemon with an added support for init and onstart functions declarable during the instantiation of the daemon. So the MiniDaemon framework remains the recommended way for simple animations, because Daemon without its collection of methods is essentially a clone of it.
- -

minidaemon.js

- -
-
/*\
-|*|
-|*|  :: MiniDaemon ::
-|*|
-|*|  Revision #2 - September 26, 2014
-|*|
-|*|  https://developer.mozilla.org/en-US/docs/Web/API/window.setInterval
-|*|  https://developer.mozilla.org/User:fusionchess
-|*|  https://github.com/madmurphy/minidaemon.js
-|*|
-|*|  This framework is released under the GNU Lesser General Public License, version 3 or later.
-|*|  http://www.gnu.org/licenses/lgpl-3.0.html
-|*|
-\*/
-
-function MiniDaemon (oOwner, fTask, nRate, nLen) {
-  if (!(this && this instanceof MiniDaemon)) { return; }
-  if (arguments.length < 2) { throw new TypeError('MiniDaemon - not enough arguments'); }
-  if (oOwner) { this.owner = oOwner; }
-  this.task = fTask;
-  if (isFinite(nRate) && nRate > 0) { this.rate = Math.floor(nRate); }
-  if (nLen > 0) { this.length = Math.floor(nLen); }
-}
-
-MiniDaemon.prototype.owner = null;
-MiniDaemon.prototype.task = null;
-MiniDaemon.prototype.rate = 100;
-MiniDaemon.prototype.length = Infinity;
-
-  /* These properties should be read-only */
-
-MiniDaemon.prototype.SESSION = -1;
-MiniDaemon.prototype.INDEX = 0;
-MiniDaemon.prototype.PAUSED = true;
-MiniDaemon.prototype.BACKW = true;
-
-  /* Global methods */
-
-MiniDaemon.forceCall = function (oDmn) {
-  oDmn.INDEX += oDmn.BACKW ? -1 : 1;
-  if (oDmn.task.call(oDmn.owner, oDmn.INDEX, oDmn.length, oDmn.BACKW) === false || oDmn.isAtEnd()) { oDmn.pause(); return false; }
-  return true;
-};
-
-  /* Instances methods */
-
-MiniDaemon.prototype.isAtEnd = function () {
-  return this.BACKW ? isFinite(this.length) && this.INDEX < 1 : this.INDEX + 1 > this.length;
-};
-
-MiniDaemon.prototype.synchronize = function () {
-  if (this.PAUSED) { return; }
-  clearInterval(this.SESSION);
-  this.SESSION = setInterval(MiniDaemon.forceCall, this.rate, this);
-};
-
-MiniDaemon.prototype.pause = function () {
-  clearInterval(this.SESSION);
-  this.PAUSED = true;
-};
-
-MiniDaemon.prototype.start = function (bReverse) {
-  var bBackw = Boolean(bReverse);
-  if (this.BACKW === bBackw && (this.isAtEnd() || !this.PAUSED)) { return; }
-  this.BACKW = bBackw;
-  this.PAUSED = false;
-  this.synchronize();
-};
-
-
- -
MiniDaemon passes arguments to the callback function. If you want to work on it with browsers that natively do not support this feature, use one of the methods proposed above.
- -

语法

- -

var myDaemon = new MiniDaemon(thisObject, callback[, rate[, length]]);

- -

说明

- -

Returns a JavaScript Object containing all information needed by an animation (like the this object, the callback function, the length, the frame-rate).

- -

参数

- -
-
thisObject
-
The this object on which the callback function is called. It can be an object or null.
-
callback
-
The function that is repeatedly invoked . It is called with three arguments: index (the iterative index of each invocation), length (the number of total invocations assigned to the daemon - finite or Infinity) and backwards (a boolean expressing whether the index is increasing or decreasing). It is something like callback.call(thisObject, index, length, backwards). If the callback function returns a false value the daemon is paused.
-
rate (optional)
-
The time lapse (in number of milliseconds) between each invocation. The default value is 100.
-
length (optional)
-
The total number of invocations. It can be a positive integer or Infinity. The default value is Infinity.
-
- -

MiniDaemon 实例(instance)的属性

- -
-
myDaemon.owner
-
The this object on which is executed the daemon (read/write). It can be an object or null.
-
myDaemon.task
-
The function that is repeatedly invoked (read/write). It is called with three arguments: index (the iterative index of each invocation), length (the number of total invocations assigned to the daemon - finite or Infinity) and backwards (a boolean expressing whether the index is decreasing or not) – see above. If the myDaemon.task function returns a false value the daemon is paused.
-
myDaemon.rate
-
The time lapse (in number of milliseconds) between each invocation (read/write).
-
myDaemon.length
-
The total number of invocations. It can be a positive integer or Infinity (read/write).
-
- -

MiniDaemon 实例的方法

- -
-
myDaemon.isAtEnd()
-
Returns a boolean expressing whether the daemon is at the start/end position or not.
-
myDaemon.synchronize()
-
Synchronize the timer of a started daemon with the time of its invocation.
-
myDaemon.pause()
-
Pauses the daemon.
-
myDaemon.start([reverse])
-
Starts the daemon forward (index of each invocation increasing) or backwards (index decreasing).
-
- -

MiniDaemon 全局对象的方法

- -
-
MiniDaemon.forceCall(minidaemon)
-
Forces a single callback to the minidaemon.task function regardless of the fact that the end has been reached or not. In any case the internal INDEX property is increased/decreased (depending on the actual direction of the process).
-
- -

使用示例

- -

HTML:

- -
<!DOCTYPE html>
-<html>
-<head>
-  <meta charset="UTF-8" />
-  <title>MiniDaemin Example - MDN</title>
-  <script type="text/javascript" src="minidaemon.js"></script>
-  <style type="text/css">
-    #sample_div {
-      visibility: hidden;
-    }
-  </style>
-</head>
-
-<body>
-  <p>
-    <input type="button" onclick="fadeInOut.start(false /* optional */);" value="fade in" />
-    <input type="button" onclick="fadeInOut.start(true);" value="fade out">
-    <input type="button" onclick="fadeInOut.pause();" value="pause" />
-  </p>
-
-  <div id="sample_div">Some text here</div>
-
-  <script type="text/javascript">
-    function opacity (nIndex, nLength, bBackwards) {
-      this.style.opacity = nIndex / nLength;
-      if (bBackwards ? nIndex === 0 : nIndex === 1) {
-        this.style.visibility = bBackwards ? 'hidden' : 'visible';
-      }
-    }
-
-    var fadeInOut = new MiniDaemon(document.getElementById('sample_div'), opacity, 300, 8);
-  </script>
-</body>
-</html>
- -

View this example in action

- -

备注

- -

The setInterval() function is commonly used to set a delay for functions that are executed again and again, such as animations.

- -

You can cancel the interval using {{domxref("WindowOrWorkerGlobalScope.clearInterval()")}}.

- -

If you wish to have your function called once after the specified delay, use {{domxref("WindowOrWorkerGlobalScope.setTimeout()")}}.

- -

Ensure that execution duration is shorter than interval frequency

- -

If there is a possibility that your logic could take longer to execute than the interval time, it is recommended that you recursively call a named function using {{domxref("WindowOrWorkerGlobalScope.setTimeout")}}. For example, if using setInterval to poll a remote server every 5 seconds, network latency, an unresponsive server, and a host of other issues could prevent the request from completing in its allotted time. As such, you may find yourself with queued up XHR requests that won't necessarily return in order.

- -

In these cases, a recursive setTimeout() pattern is preferred:

- -
(function loop(){
-   setTimeout(function() {
-      // Your logic here
-
-      loop();
-  }, delay);
-})();
-
- -

In the above snippet, a named function loop() is declared and is immediately executed. loop() is recursively called inside setTimeout() after the logic has completed executing. While this pattern does not guarantee execution on a fixed interval, it does guarantee that the previous interval has completed before recursing.

- -

Throttling of intervals

- -

setInterval() is subject to the same throttling restrictions in Firefox as {{domxref("WindowOrWorkerGlobalScope.setTimeout","setTimeout()")}}; see Reasons for delays longer than specified.

- -

规范

- - - - - - - - - - - - - - - - - - - -
SpecificationStatusComment
{{SpecName('HTML WHATWG', 'webappapis.html#dom-setinterval', 'WindowOrWorkerGlobalScope.setInterval()')}}{{Spec2("HTML WHATWG")}}Method moved to the WindowOrWorkerGlobalScope mixin in the latest spec.
{{SpecName("HTML WHATWG", "webappapis.html#dom-setinterval", "WindowTimers.setInterval()")}}{{Spec2("HTML WHATWG")}}Initial definition (DOM Level 0)
- -

浏览器兼容性

- -
- - -

{{Compat("api.WindowOrWorkerGlobalScope.setInterval")}}

-
- -

参见

- - diff --git a/files/zh-cn/web/api/windoworworkerglobalscope/settimeout/index.html b/files/zh-cn/web/api/windoworworkerglobalscope/settimeout/index.html deleted file mode 100644 index d0c80bb95b..0000000000 --- a/files/zh-cn/web/api/windoworworkerglobalscope/settimeout/index.html +++ /dev/null @@ -1,477 +0,0 @@ ---- -title: window.setTimeout -slug: Web/API/WindowOrWorkerGlobalScope/setTimeout -tags: - - Timers - - WindowOrWorkerGlobalScope - - WindowTimers - - setTimeout -translation_of: Web/API/WindowOrWorkerGlobalScope/setTimeout -original_slug: Web/API/Window/setTimeout ---- -

{{APIRef("HTML DOM")}}

- -

 {{domxref("WindowOrWorkerGlobalScope")}} 混合的 setTimeout()方法设置一个定时器,该定时器在定时器到期后执行一个函数或指定的一段代码。

- -

语法

- -
var timeoutID = scope.setTimeout(function[, delay, arg1, arg2, ...]);
-var timeoutID = scope.setTimeout(function[, delay]);
-var timeoutID = scope.setTimeout(code[, delay]);
- -

参数

- -
-
function
-
{{jsxref("function")}} 是你想要在到期时间(delay毫秒)之后执行的函数
-
code
-
这是一个可选语法,你可以使用字符串而不是{{jsxref("function")}} ,在delay毫秒之后编译和执行字符串 (使用该语法是不推荐的, 原因和使用 {{jsxref("Global_Objects/eval", "eval()")}}一样,有安全风险)。
-
delay {{optional_inline}}
-
延迟的毫秒数 (一秒等于1000毫秒),函数的调用会在该延迟之后发生。如果省略该参数,delay取默认值0,意味着“马上”执行,或者尽快执行。不管是哪种情况,实际的延迟时间可能会比期待的(delay毫秒数) 值长,原因请查看{{anch("实际延时比设定值更久的原因:最小延迟时间")}}。
-
arg1, ..., argN {{optional_inline}}
-
附加参数,一旦定时器到期,它们会作为参数传递给{{jsxref("function")}} 
-
- -
-

备注:需要注意的是,IE9 及更早的 IE 浏览器不支持向回调函数传递额外参数(第一种语法)。如果你想要在IE中达到同样的功能,你必须使用一种兼容代码 (查看  {{anch("兼容旧环境(polyfill)")}} 一段).

-
- -

返回值

- -

返回值timeoutID是一个正整数,表示定时器的编号。这个值可以传递给{{domxref("WindowOrWorkerGlobalScope.clearTimeout","clearTimeout()")}}来取消该定时器。

- -

需要注意的是setTimeout()和{{domxref("WindowOrWorkerGlobalScope.setInterval", "setInterval()")}}共用一个编号池,技术上,clearTimeout()和 {{domxref("WindowOrWorkerGlobalScope.clearInterval", "clearInterval()")}} 可以互换。但是,为了避免混淆,不要混用取消定时函数。

- -

在同一个对象上(一个window或者worker),setTimeout()或者setInterval()在后续的调用不会重用同一个定时器编号。但是不同的对象使用独立的编号池。

- -

例子

- -

下文的例子在网页中设置了两个简单的按钮,以触发 setTimeout() 和 clearTimeout() 方法:按下第一个按钮会设置一个定时器,定时器在 2s 后显示一个警告对话框,并将此次 setTimeout 的定时器 ID 保存起来,按下第二个按钮可以取消定时器。

- -

HTML

- -
<p>Live Example</p>
-<button onclick="delayedAlert();">Show an alert box after two seconds</button>
-<p></p>
-<button onclick="clearAlert();">Cancel alert before it happens</button>
-
- -
- -
- -
- -
- -

JavaScript

- -
var timeoutID;
-
-function delayedAlert() {
-  timeoutID = window.setTimeout(slowAlert, 2000);
-}
-
-function slowAlert() {
-  alert('That was really slow!');
-}
-
-function clearAlert() {
-  window.clearTimeout(timeoutID);
-}
-
- -
- -
- -
- -
- -
- -
- -
- -
- -
- -
- -
- -
- -
- -

结果展示

- -

{{EmbedLiveSample('例子')}}

- -

也可参考 clearTimeout() 示例.

- -

兼容旧环境(polyfill)

- -

如果你需要向你的回调函数内传递一个或多个参数, 而且还需要兼容那些不支持传递额外参数(不管使用setTimeout() 或者 setInterval())的浏览器时(比如,IE9及更早的版本), 你可以引入下面的兼容代码来支持向定时器函数传参。将以下代码添加到你代码的最上面:

- -
/*\
-|*|
-|*|  Polyfill which enables the passage of arbitrary arguments to the
-|*|  callback functions of JavaScript timers (HTML5 standard syntax).
-|*|
-|*|  https://developer.mozilla.org/en-US/docs/DOM/window.setInterval
-|*|
-|*|  Syntax:
-|*|  var timeoutID = window.setTimeout(func, delay[, param1, param2, ...]);
-|*|  var timeoutID = window.setTimeout(code, delay);
-|*|  var intervalID = window.setInterval(func, delay[, param1, param2, ...]);
-|*|  var intervalID = window.setInterval(code, delay);
-|*|
-\*/
-
-(function() {
-  setTimeout(function(arg1) {
-    if (arg1 === 'test') {
-      // feature test is passed, no need for polyfill
-      return;
-    }
-    var __nativeST__ = window.setTimeout;
-    window.setTimeout = function(vCallback, nDelay /*, argumentToPass1, argumentToPass2, etc. */ ) {
-      var aArgs = Array.prototype.slice.call(arguments, 2);
-      return __nativeST__(vCallback instanceof Function ? function() {
-        vCallback.apply(null, aArgs);
-      } : vCallback, nDelay);
-    };
-  }, 0, 'test');
-
-  var interval = setInterval(function(arg1) {
-    clearInterval(interval);
-    if (arg1 === 'test') {
-      // feature test is passed, no need for polyfill
-      return;
-    }
-    var __nativeSI__ = window.setInterval;
-    window.setInterval = function(vCallback, nDelay /*, argumentToPass1, argumentToPass2, etc. */ ) {
-      var aArgs = Array.prototype.slice.call(arguments, 2);
-      return __nativeSI__(vCallback instanceof Function ? function() {
-        vCallback.apply(null, aArgs);
-      } : vCallback, nDelay);
-    };
-  }, 0, 'test');
-}())
- -

针对IE的解决方法

- -

如果你需要单独的针对IE9及之前浏览器的 hack 写法,你可以使用 JavaScript 条件注释:

- -
/*@cc_on
-  // conditional IE < 9 only fix
-  @if (@_jscript_version <= 9)
-  (function(f){
-     window.setTimeout = f(window.setTimeout);
-     window.setInterval = f(window.setInterval);
-  })(function(f){return function(c,t){var a=[].slice.call(arguments,2);return f(function(){c instanceof Function?c.apply(this,a):eval(c)},t)}});
-  @end
-@*/
- -
- -
- -
- -
- -
- -
- -
- -
- -
- -

或者使用更加清晰的 IE HTML 条件注释:

- -
<!--[if lte IE 9]><script>
-(function(f){
-window.setTimeout=f(window.setTimeout);
-window.setInterval=f(window.setInterval);
-})(function(f){return function(c,t){
-var a=[].slice.call(arguments,2);return f(function(){c instanceof Function?c.apply(this,a):eval(c)},t)}
-});
-</script><![endif]-->
-
-
-
- -
- -
- -

变通方法

- -

另一种方法是使用匿名函数包裹你的回调函数,这种方式要消耗更多资源:

- -
var intervalID = setTimeout(function() { myFunc('one', 'two', 'three'); }, 1000);
-
- -
- -

上面那个例子也可以用箭头函数:

- -
var intervalID = setTimeout(() => { myFunc('one', 'two', 'three'); }, 1000);
-
- -

此外,也可使用 function's bind

- -
setTimeout(function(arg1){}.bind(undefined, 10), 1000);
-
- -

关于"this"的问题

- -

当你向 setTimeout() (或者其他函数)传递一个函数时,该函数中的this指向跟你的期望可能不同,这个问题在 JavaScript reference 中进行了详细解释.

- -

解释

- -

setTimeout()调用的代码运行在与所在函数完全分离的执行环境上。这会导致,这些代码中包含的 this 关键字在非严格模式会指向 window (或全局)对象,严格模式下为 undefined,这和所期望的this的值是不一样的。

- -
-

备注:即使是在严格模式下,setTimeout()的回调函数里面的this仍然默认指向window对象, 并不是undefined

-
- -

查看下面的例子:

- -
let myArray = ["zero", "one", "two"];
-myArray.myMethod = function (sProperty) {
-    alert(arguments.length > 0 ? this[sProperty] : this);
-};
-
-myArray.myMethod(); // prints "zero,one,two"
-myArray.myMethod(1); // prints "one"
- -

上面这段代码正常工作,用myArray调用,在函数内,this[sProperty]等于 myArray[sProperty]。然后,下面这个例子:

- -
setTimeout(myArray.myMethod, 1000); // prints "[object Window]" after 1 second
-setTimeout(myArray.myMethod, 1500, "1"); // prints "undefined" after 1.5 seconds
- -

myArray.myMethod函数传递给 setTimeout,到了定时时间,this没有指向,默认指向window对象。并且没有方法把 thisArg 传递给setTimeout,正如Array方法的forEachreduce等。下面的例子表示使用call方法设置this也没用。

- -
setTimeout.call(myArray, myArray.myMethod, 2000); // error: "NS_ERROR_XPC_BAD_OP_ON_WN_PROTO: Illegal operation on WrappedNative prototype object"
-setTimeout.call(myArray, myArray.myMethod, 2500, 2); // same error
- -

可能的解决方案

- -

一个通用的方法是用包装函数来设置this

- -
setTimeout(function(){myArray.myMethod()}, 2000); // prints "zero,one,two" after 2 seconds
-setTimeout(function(){myArray.myMethod('1')}, 2500); // prints "one" after 2.5 seconds
- -

箭头函数也可以:

- -
setTimeout(() => {myArray.myMethod()}, 2000); // prints "zero,one,two" after 2 seconds
-setTimeout(() => {myArray.myMethod('1')}, 2500); // prints "one" after 2.5 seconds
- -

另一个解决this问题的方法是使用两个非原生的 setTimeout()setInterval() 全局函数代替原生的。该非原生的函数通过使用Function.prototype.call 方法激活了正确的作用域。下面的代码显示了应该如何替换:

- -
// Enable the passage of the 'this' object through the JavaScript timers
-
-var __nativeST__ = window.setTimeout, __nativeSI__ = window.setInterval;
-
-window.setTimeout = function (vCallback, nDelay /*, argumentToPass1, argumentToPass2, etc. */) {
-  var oThis = this, aArgs = Array.prototype.slice.call(arguments, 2);
-  return __nativeST__(vCallback instanceof Function ? function () {
-    vCallback.apply(oThis, aArgs);
-  } : vCallback, nDelay);
-};
-
-window.setInterval = function (vCallback, nDelay /*, argumentToPass1, argumentToPass2, etc. */) {
-  var oThis = this, aArgs = Array.prototype.slice.call(arguments, 2);
-  return __nativeSI__(vCallback instanceof Function ? function () {
-    vCallback.apply(oThis, aArgs);
-  } : vCallback, nDelay);
-};
- -
备注: 这两个替换也让 IE支持了符合 HTML5 标准的定时器函数。所以也能作为一个 polyfills。查看 Callback arguments 一段.
- -

新特性检测:

- -
let myArray = ["zero", "one", "two"];
-myArray.myMethod = function (sProperty) {
-    alert(arguments.length > 0 ? this[sProperty] : this);
-};
-
-setTimeout(alert, 1500, "Hello world!"); // the standard use of setTimeout and setInterval is preserved, but...
-setTimeout.call(myArray, myArray.myMethod, 2000); // prints "zero,one,two" after 2 seconds
-setTimeout.call(myArray, myArray.myMethod, 2500, 2); // prints "two" after 2,5 seconds
-
- -

针对这个问题并没有原生的解决方案。

- -
注:JavaScript 1.8.5 引入了 Function.prototype.bind() 方法,该方法允许显式地指定函数调用时 this 所指向的值 。该方法可以帮助你解决 this 指向不确定的问题。
- -

使用bind()的例子:

- -
let myArray = ['zero', 'one', 'two'];
-myBoundMethod = (function (sProperty) {
-    console.log(arguments.length > 0 ? this[sProperty] : this);
-}).bind(myArray);
-
-myBoundMethod(); // prints "zero,one,two" because 'this' is bound to myArray in the function
-myBoundMethod(1); // prints "one"
-setTimeout(myBoundMethod, 1000); // still prints "zero,one,two" after 1 second because of the binding
-setTimeout(myBoundMethod, 1500, "1"); // prints "one" after 1.5 seconds
-
- -

备注

- -

你可以使用 {{domxref("WindowOrWorkerGlobalScope.clearTimeout()","clearTimeout()")}}来取消定时器。

- -

如果你希望你的代码被重复的调用 (比如每 N 毫秒一次),考虑使用{{domxref("WindowOrWorkerGlobalScope.setInterval()","setInterval()")}}。

- -

传递字符串字面量

- -

setTimeout()传递一个字符串而不是函数会遭受到与使用eval一样的风险.

- -
// 推荐
-window.setTimeout(function() {
-    alert("Hello World!");
-}, 500);
-
-// 不推荐
-window.setTimeout("alert(\"Hello World!\");", 500);
-
-
- -

字符串会在全局作用域内被解释执行,所以当setTimeout()函数执行完毕后,字符串中的变量不可用.

- -

实际延时比设定值更久的原因:最小延迟时间

- -

有很多因素会导致setTimeout的回调函数执行比设定的预期值更久,本节将讨论最常见的原因。

- -

最小延时 >=4ms

- -

在浏览器中,setTimeout()/{{domxref("WindowOrworkerGlobalScope.setInterval","setInterval()")}} 的每调用一次定时器的最小间隔是4ms,这通常是由于函数嵌套导致(嵌套层级达到一定深度),或者是由于已经执行的setInterval的回调函数阻塞导致的。例如:

- -
function cb() { f(); setTimeout(cb, 0); }
-setTimeout(cb, 0);
- -
setInterval(f, 0);
- -

在Chrome 和 Firefox中, 定时器的第5次调用被阻塞了;在Safari是在第6次;Edge是在第3次。Gecko 从这个版本 version 56开始对 setInterval() 开始采用这样的机制(setTimeout()已经实现,具体请参考以下内容)。

- -

一直以来,不同浏览器中出现这种最小延迟的情况有所不同(例如Firefox) - 从其他地方调用了setInterval( ),或者在嵌套函数调用setTimeout( ) 时(嵌套级别达到特定深度时),都会出现超时延迟。

- -

如果想在浏览器中实现0ms延时的定时器,你可以参考这里所说的{domxref("window.postMessage()")}}

- -
-

Note: 最小延时, DOM_MIN_TIMEOUT_VALUE, 是4ms  (但在Firefox中通常是是存储在 dom.min_timeout_value 这个变量中), DOM_CLAMP_TIMEOUT_NESTING_LEVEL 的第5层.

-
- -
-

Note: 4 ms 是在  HTML5 spec  中精确的,并且在2010年及以后的跨浏览器中保持了一致,这个数值比 {{geckoRelease("5.0")}}规定的嵌套函数的最小延时10ms更为精确。

-
- -

未被激活的tabs的定时最小延迟>=1000ms

- -

为了优化后台tab的加载损耗(以及降低耗电量),在未被激活的tab中定时器的最小延时限制为1S(1000ms)。

- -

Firefox 从version 5 (see {{bug(633421)}}开始采取这种机制,1000ms的间隔值可以通过 dom.min_background_timeout_value 改变。Chrome 从 version 11 (crbug.com/66078)开始采用。

- -

Android 版的Firefox对未被激活的后台tabs的使用了15min的最小延迟间隔时间 ,并且这些tabs也能完全不被加载。

- -
-

当 Web Audio API {{domxref("AudioContext")}} 正在被用来播放音频的时候,Firefox 50不会再限制后台tabs的加载。 后续的Firefox 51 版本修正了这个问题,即使在没有音频播放的情况下,也不再限制后台tabs的加载。这个解决了一些软件应用在后台tabs中播放基于文本的音频( note-based) 时,无法去同步音频和画面的问题。

-
- -

追踪型脚本的最小延时限制

- -

从Firefox 55版本开始,追踪型脚本(例如 谷歌分析,或者其他的一些被Firefox 的 TP lists 识别为追踪型脚本的 外链URL脚本)是重点限制加载的对象。在当前正在使用的页面中,这个节流限制的延时依然是4ms。但是在后台tabs中,这个最小延时限制是10000ms(10s),这个限制会在文档第一次加载后的30s后生效。

- -

控制这些行为的属性包含以下这些:

- - - -

超时延迟

- -

除了"最小延时"之外,定时器仍然有可能因为当前页面(或者操作系统/浏览器本身)被其他任务占用导致延时。 需要被强调是, 直到调用 setTimeout()的主线程执行完其他任务之后,回调函数和代码段才能被执行。例如:

- -
function foo() {
-  console.log('foo has been called');
-}
-setTimeout(foo, 0);
-console.log('After setTimeout');
- -

会在控制台输出:

- -
After setTimeout
-foo has been called
- -

出现这个结果的原因是,尽管setTimeout 以0ms的延迟来调用函数,但这个任务已经被放入了队列中并且等待下一次执行;并不是立即执行;队列中的等待函数被调用之前,当前代码必须全部运行完毕,因此这里运行结果并非预想的那样。

- -

WebExtension Background pages和定时器

- -

在 WebExtension 中 background pages,timers工作不正常。这主要因为background pages实际上,并不是一次性全部加载:如果浏览器没有使用它,就不加载,如果需要就恢复。这对于WebExtension是透明的,但是有些事件(包括JS的timers)不会在不加载/恢复循环中执行,所以WebExtension中建议使用alarms。更详细的细节在合并到事件驱动后台脚本

- -

在本文写作的时候,只有Chrome展示了如上的特性 — Firefox没有未加载/恢复循环的行为,所以timers仍然可以工作。但是,仍然建议不要在WebExtension中使用timers:

- -

1.兼容Chorme。

- -

2.未来行为的改变会引起问题。

- -

最大延时值

- -

包括 IE,  Chrome, Safari, Firefox 在内的浏览器其内部以32位带符号整数存储延时。这就会导致如果一个延时(delay)大于 2147483647 毫秒 (大约24.8 天)时就会溢出,导致定时器将会被立即执行。

- -

规范

- - - - - - - - - - - - - - - - - - - - - -
SpecificationStatusComment
{{SpecName('HTML WHATWG', 'webappapis.html#dom-settimeout', 'WindowOrWorkerGlobalScope.setTimeout()')}}{{Spec2("HTML WHATWG")}}Method moved to the WindowOrWorkerGlobalScope mixin in the latest spec.
{{SpecName("HTML WHATWG", "webappapis.html#dom-settimeout", "WindowTimers.setTimeout()")}}{{Spec2("HTML WHATWG")}}Initial definition (DOM Level 0)
- -

浏览器兼容性

- -
- - -

{{Compat("api.WindowOrWorkerGlobalScope.setTimeout")}}

-
- -

相关链接:

- - -- cgit v1.2.3-54-g00ecf