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/ja/web/api/atob/index.html | 92 +++ files/ja/web/api/btoa/index.html | 145 +++++ files/ja/web/api/caches/index.html | 83 +++ files/ja/web/api/clearinterval/index.html | 67 +++ files/ja/web/api/cleartimeout/index.html | 101 ++++ files/ja/web/api/createimagebitmap/index.html | 104 ++++ files/ja/web/api/fetch/index.html | 192 +++++++ files/ja/web/api/indexeddb/index.html | 72 +++ files/ja/web/api/issecurecontext/index.html | 57 ++ files/ja/web/api/origin/index.html | 59 ++ files/ja/web/api/setinterval/index.html | 636 +++++++++++++++++++++ files/ja/web/api/settimeout/index.html | 420 ++++++++++++++ .../api/windoworworkerglobalscope/atob/index.html | 92 --- .../api/windoworworkerglobalscope/btoa/index.html | 144 ----- .../windoworworkerglobalscope/caches/index.html | 83 --- .../clearinterval/index.html | 67 --- .../cleartimeout/index.html | 100 ---- .../createimagebitmap/index.html | 103 ---- .../api/windoworworkerglobalscope/fetch/index.html | 191 ------- .../windoworworkerglobalscope/indexeddb/index.html | 71 --- .../issecurecontext/index.html | 56 -- .../windoworworkerglobalscope/origin/index.html | 58 -- .../setinterval/index.html | 635 -------------------- .../settimeout/index.html | 419 -------------- 24 files changed, 2028 insertions(+), 2019 deletions(-) create mode 100644 files/ja/web/api/atob/index.html create mode 100644 files/ja/web/api/btoa/index.html create mode 100644 files/ja/web/api/caches/index.html create mode 100644 files/ja/web/api/clearinterval/index.html create mode 100644 files/ja/web/api/cleartimeout/index.html create mode 100644 files/ja/web/api/createimagebitmap/index.html create mode 100644 files/ja/web/api/fetch/index.html create mode 100644 files/ja/web/api/indexeddb/index.html create mode 100644 files/ja/web/api/issecurecontext/index.html create mode 100644 files/ja/web/api/origin/index.html create mode 100644 files/ja/web/api/setinterval/index.html create mode 100644 files/ja/web/api/settimeout/index.html delete mode 100644 files/ja/web/api/windoworworkerglobalscope/atob/index.html delete mode 100644 files/ja/web/api/windoworworkerglobalscope/btoa/index.html delete mode 100644 files/ja/web/api/windoworworkerglobalscope/caches/index.html delete mode 100644 files/ja/web/api/windoworworkerglobalscope/clearinterval/index.html delete mode 100644 files/ja/web/api/windoworworkerglobalscope/cleartimeout/index.html delete mode 100644 files/ja/web/api/windoworworkerglobalscope/createimagebitmap/index.html delete mode 100644 files/ja/web/api/windoworworkerglobalscope/fetch/index.html delete mode 100644 files/ja/web/api/windoworworkerglobalscope/indexeddb/index.html delete mode 100644 files/ja/web/api/windoworworkerglobalscope/issecurecontext/index.html delete mode 100644 files/ja/web/api/windoworworkerglobalscope/origin/index.html delete mode 100644 files/ja/web/api/windoworworkerglobalscope/setinterval/index.html delete mode 100644 files/ja/web/api/windoworworkerglobalscope/settimeout/index.html (limited to 'files/ja/web') diff --git a/files/ja/web/api/atob/index.html b/files/ja/web/api/atob/index.html new file mode 100644 index 0000000000..96eb707a54 --- /dev/null +++ b/files/ja/web/api/atob/index.html @@ -0,0 +1,92 @@ +--- +title: WindowOrWorkerGlobalScope.atob() +slug: Web/API/atob +tags: + - API + - HTML DOM + - Method + - Reference + - WindowOrWorkerGlobalScope + - atob +translation_of: Web/API/WindowOrWorkerGlobalScope/atob +original_slug: Web/API/WindowOrWorkerGlobalScope/atob +--- +

{{APIRef("HTML DOM")}}

+ +

WindowOrWorkerGlobalScope.atob() 関数は、 {{glossary("Base64")}} エンコーディングでエンコードされたデータの文字列をデコードします。 {{domxref("WindowOrWorkerGlobalScope.btoa","btoa()")}} メソッドを使用して、通信に問題が発生する可能性のあるデータをエンコードして送信し、送信した後に atob() メソッドを使用して再度デコードすることができます。例えば、ASCII の 0 から 31 までのコードような制御文字をエンコードして送信し、デコードすることができます。

+ +

Unicode や UTF-8 文字列の使用については、 {{domxref("WindowOrWorkerGlobalScope.btoa", "btoa()")}} の「Uncode 文字列」の節を参照してください。

+ +

構文

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

引数

+ +
+
encodedData
+
エンコードされたデータが入っているバイナリ文字列です。
+
+ +

返値

+ +

encodedData をデコードしたデータを含む ASCII 文字列です。

+ +

例外

+ +
+
{{domxref("DOMException")}} (name: InvalidCharacterError)
+
encodedData が妥当な base64 ではない場合に発行されます。
+
+ +

+ +
const encodedData = window.btoa('Hello, world'); // 文字列をエンコード
+const decodedData = window.atob(encodedData); // 文字列をデコード
+ +

ポリフィル

+ +

対応していないブラウザーでは、 https://github.com/MaxArt2501/base64-js/blob/master/base64.js のポリフィルを利用することができます。

+ +

仕様書

+ + + + + + + + + + + + + + + + + + + + + + + + + + +
仕様書状態備考
{{SpecName('HTML WHATWG', '#dom-atob', 'WindowOrWorkerGlobalScope.atob()')}}{{Spec2('HTML WHATWG')}}最新の仕様で、メソッドを WindowOrWorkerGlobalScope ミックスインに移動。
{{SpecName('HTML5.1', '#dom-windowbase64-atob', 'WindowBase64.atob()')}}{{Spec2('HTML5.1')}}{{SpecName("HTML WHATWG")}} のスナップショット、変更なし。
{{SpecName("HTML5 W3C", "#dom-windowbase64-atob", "WindowBase64.atob()")}}{{Spec2('HTML5 W3C')}}{{SpecName("HTML WHATWG")}} のスナップショット。 WindowBase64 の作成 (以前の対象だったプロパティ)。
+ +

ブラウザーの互換性

+ +
+

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

+
+ +

関連情報

+ + diff --git a/files/ja/web/api/btoa/index.html b/files/ja/web/api/btoa/index.html new file mode 100644 index 0000000000..69b1ec384a --- /dev/null +++ b/files/ja/web/api/btoa/index.html @@ -0,0 +1,145 @@ +--- +title: WindowOrWorkerGlobalScope.btoa() +slug: Web/API/btoa +tags: + - API + - HTML DOM + - Method + - Reference + - Web + - WindowOrWorkerGlobalScope + - btoa + - data + - strings +translation_of: Web/API/WindowOrWorkerGlobalScope/btoa +original_slug: Web/API/WindowOrWorkerGlobalScope/btoa +--- +

{{APIRef("HTML DOM")}}

+ +

WindowOrWorkerGlobalScope.btoa() メソッドは、 {{glossary("Base64")}} でエンコードされた ASCII 文字列をバイナリ文字列 (例えば {{jsxref("String")}} オブジェクトのうち、文字列中のすべての文字がバイナリデータのバイトとして扱うことができるもの) から生成します。

+ +

このメソッドを使用すると、通信に支障をきたす可能性のあるデータをエンコードして送信し、その後 {{domxref("WindowOrWorkerGlobalScope.atob", "atob()")}} メソッドを使用して再度デコードすることができます。例えば ASCII で 0 から 31 の値ような制御文字をエンコードすることもできます。

+ +

構文

+ +
var encodedData = scope.btoa(stringToEncode);
+ +

引数

+ +
+
stringToEncode
+
エンコードするバイナリ文字列です。
+
+ +

返値

+ +

stringToEncode の Base64 表現である ASCII 文字列です。

+ +

例外

+ +
+
InvalidCharacterError
+
文字列には、1 バイトに収まらない文字が含まれていた場合。詳細は後述の「Unicode文字列」を参照してください。
+
+ +

+ +
const encodedData = window.btoa('Hello, world'); // 文字列をエンコード
+const decodedData = window.atob(encodedData); // 文字列をデコード
+
+ +

Unicode 文字列

+ +

btoa() 関数は、JavaScript の文字列を引数にとります。JavaScript の文字列は UTF-16 文字エンコーディングで表現されます。このエンコーディングでは、文字列は 16 ビット (2 バイト) 単位の並びとして表現されます。すべての ASCII 文字はこれらの単位の 1 バイト目に収まりますが、他の多くの文字は収まりません。

+ +

Base64 は、設計上、バイナリデータを入力として期待します。 JavaScript の文字列では、これは各文字が 1 バイトしか占有しない文字列を意味します。したがって、2 バイト以上の文字を含む文字列を btoa() に渡した場合、これはバイナリデータとはみなされないため、エラーが発生します。

+ +
const ok = "a";
+console.log(ok.codePointAt(0).toString(16)); //   61: 長さ < 1 バイト
+
+const notOK = "✓"
+console.log(notOK.codePointAt(0).toString(16)); // 2713: 長さ > 1 バイト
+
+console.log(btoa(ok));    // YQ==
+console.log(btoa(notOK)); // error
+ +

btoa() を用いて Unicode テキストを ASCII としてエンコードする必要がある場合、一つの選択肢として、各 16 ビット単位が 1 バイトしか占有しないように文字列を変換することができます。例えば、以下のようになります。

+ +
// Unicode 文字列で、各 16 ビット単位を 1 バイトしか占有
+// しない文字列に変換します。
+function toBinary(string) {
+  const codeUnits = new Uint16Array(string.length);
+  for (let i = 0; i < codeUnits.length; i++) {
+    codeUnits[i] = string.charCodeAt(i);
+  }
+  return String.fromCharCode(...new Uint8Array(codeUnits.buffer));
+}
+
+// 1 バイトを超える文字を含んだ文字列
+const myString = "☸☹☺☻☼☾☿";
+
+const converted = toBinary(myString);
+const encoded = btoa(converted);
+console.log(encoded);                 // OCY5JjomOyY8Jj4mPyY=
+
+ +

このようにした場合、当然ながらデコードされた文字列を逆変換する必要があります。

+ +
function fromBinary(binary) {
+  const bytes = new Uint8Array(binary.length);
+  for (let i = 0; i < bytes.length; i++) {
+    bytes[i] = binary.charCodeAt(i);
+  }
+  return String.fromCharCode(...new Uint16Array(bytes.buffer));
+}
+
+const decoded = atob(encoded);
+const original = fromBinary(decoded);
+console.log(original);                // ☸☹☺☻☼☾☿
+
+ +

ポリフィル

+ +

対応していないブラウザーでは、 https://github.com/MaxArt2501/base64-js/blob/master/base64.js のポリフィルを利用することができます。

+ +

仕様書

+ + + + + + + + + + + + + + + + + + + + + + + + + + +
仕様書状態備考
{{SpecName('HTML WHATWG', '#dom-btoa', 'WindowOrWorkerGlobalScope.btoa()')}}{{Spec2('HTML WHATWG')}}最新の仕様で、メソッドを WindowOrWorkerGlobalScope ミックスインに移動。
{{SpecName('HTML5.1', '#dom-windowbase64-btoa', 'WindowBase64.btoa()')}}{{Spec2('HTML5.1')}}{{SpecName("HTML WHATWG")}} のスナップショット、変更なし。
{{SpecName("HTML5 W3C", "#dom-windowbase64-btoa", "WindowBase64.btoa()")}}{{Spec2('HTML5 W3C')}}{{SpecName("HTML WHATWG")}} のスナップショット。 WindowBase64 の作成 (properties where on the target before it).
+ +

ブラウザーの互換性

+ +
+

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

+
+ +

関連情報

+ + diff --git a/files/ja/web/api/caches/index.html b/files/ja/web/api/caches/index.html new file mode 100644 index 0000000000..24bcabe2aa --- /dev/null +++ b/files/ja/web/api/caches/index.html @@ -0,0 +1,83 @@ +--- +title: WorkerGlobalScope.caches +slug: Web/API/caches +tags: + - API + - Experimental + - Property + - Read-only + - Reference + - Service Workers + - Web Workers + - Window + - WindowOrWorkerGlobalScope +translation_of: Web/API/WindowOrWorkerGlobalScope/caches +original_slug: Web/API/WindowOrWorkerGlobalScope/caches +--- +
{{APIRef()}}{{SeeCompatTable}}
+ +

{{domxref("WindowOrWorkerGlobalScope")}} インターフェイスの caches 読み取り専用プロパティは、現在のワーカーコンテキストに関連する {{domxref("CacheStorage")}} オブジェクトを返します。このオブジェクトにより、オフライン利用のために資産 (assets、アセット) を保存したり、リクエストに対するカスタムレスポンスを生成したりするなどの機能を使用できます。

+ +

構文

+ +
var myCacheStorage = self.caches; // または単に caches
+
+ +

+ +

{{domxref("CacheStorage")}}。

+ +

+ +

次の例では、アセットをオフラインで利用できるようにするために、ServiceWorker コンテキストでキャッシュを使う方法を示しています。

+ +
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'
+      );
+    })
+  );
+});
+ +

仕様

+ + + + + + + + + + + + + + +
仕様ステータスコメント
{{SpecName('Service Workers')}}{{Spec2('Service Workers')}}初期定義。
+ +

ブラウザー実装状況

+ + + +

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

+ +

関連項目

+ + diff --git a/files/ja/web/api/clearinterval/index.html b/files/ja/web/api/clearinterval/index.html new file mode 100644 index 0000000000..3bccc06f99 --- /dev/null +++ b/files/ja/web/api/clearinterval/index.html @@ -0,0 +1,67 @@ +--- +title: window.clearInterval +slug: Web/API/clearInterval +tags: + - DOM + - DOM_0 + - Gecko + - JavaScript timers + - Window +translation_of: Web/API/WindowOrWorkerGlobalScope/clearInterval +original_slug: Web/API/WindowOrWorkerGlobalScope/clearInterval +--- +
{{ApiRef}}
+ +

概要

+ +

{{domxref("window.setInterval", "setInterval")}} を使用して設定された繰り返し動作をキャンセルします。

+ +

構文

+ +
window.clearInterval(intervalID)
+
+ + + +

+ +

{{domxref("window.setInterval", "setInterval()", "example")}} の例を参照して下さい。

+ +

仕様

+ + + + + + + + + + + + + + + + + + + +
仕様書策定状況コメント
{{SpecName('HTML WHATWG', 'webappapis.html#dom-setInterval', 'WindowOrWorkerGlobalScope.clearInterval()')}}{{Spec2("HTML WHATWG")}}最新の仕様で、メソッドを WindowOrWorkerGlobalScope ミックスインに移動。
{{SpecName("HTML WHATWG", "webappapis.html#dom-setInterval", "WindowTimers.setInterval()")}}{{Spec2("HTML WHATWG")}} 
+ +

ブラウザー実装状況

+ +

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

+ +

関連情報

+ + diff --git a/files/ja/web/api/cleartimeout/index.html b/files/ja/web/api/cleartimeout/index.html new file mode 100644 index 0000000000..bc1b59314e --- /dev/null +++ b/files/ja/web/api/cleartimeout/index.html @@ -0,0 +1,101 @@ +--- +title: WindowOrWorkerGlobalScope.clearTimeout() +slug: Web/API/clearTimeout +tags: + - API + - HTML DOM + - Method + - Reference + - WindowOrWorkerGlobalScope + - clearTimeout + - メソッド + - リファレンス +translation_of: Web/API/WindowOrWorkerGlobalScope/clearTimeout +original_slug: Web/API/WindowOrWorkerGlobalScope/clearTimeout +--- +
{{APIRef("HTML DOM")}}
+ +

clearTimeout() は {{domxref("WindowOrWorkerGlobalScope")}} ミックスインのメソッドで、以前の {{domxref("WindowOrWorkerGlobalScope.setTimeout", "setTimeout()")}} の呼び出しによって以前に確立されたタイムアウトを解除します。

+ +

構文

+ +
scope.clearTimeout(timeoutID)
+
+ +

引数

+ +
+
timeoutID
+
解除したいタイマの ID です。 ID は setTimeout() の返値によって取得できます。
+
+ +

注目すべきは、 {{domxref("WindowOrWorkerGlobalScope.setTimeout", "setTimeout()")}} および {{domxref("WindowOrWorkerGlobalScope.setInterval", "setInterval()")}} で使用される ID のプールは共有されますので、技術的には clearTimeout() および {{domxref("WindowOrWorkerGlobalScope.clearInterval", "clearInterval()")}} は互いに交換できます。しかし、明確化のため、そのようなことは避けてください。

+ +

+ +

ウェブページのコンテキストで以下のスクリプトを実行し、ページを一度クリックしてください。1秒後にメッセージがポップアップします。1秒間に複数回ページをクリックしても、アラートは一度しか表示されません。

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

メモ

+ +

clearTimeout() へ妥当ではない ID を渡しても、何の効果もありません。例外は発生しません。

+ +

仕様書

+ + + + + + + + + + + + + + + + + + + + + +
仕様書状態備考
{{SpecName('HTML WHATWG', 'webappapis.html#dom-cleartimeout', 'WindowOrWorkerGlobalScope.clearTimeout()')}}{{Spec2("HTML WHATWG")}}最新の仕様で、メソッドを WindowOrWorkerGlobalScope ミックスインに移動。
{{SpecName('HTML WHATWG', 'webappapis.html#dom-cleartimeout', 'clearTimeout()')}}{{Spec2('HTML WHATWG')}}
+ +

ブラウザーの互換性

+ +

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

+ +

関連情報

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

createImageBitmap() メソッドは、指定されたソースからビットマップを作成します。このメソッドは、windows と worker の両方のグローバルスコープに存在します。このメソッドは、さまざまな異なる画像ソースを受け付け、{{domxref("Promise")}} を返し、{{domxref("ImageBitmap")}} に解決します。

+ +

シンタックス

+ +
const imageBitmapPromise = createImageBitmap(image[, options]);
+const imageBitmapPromise = createImageBitmap(image, sx, sy, sw, sh[, options]);
+ +

パラメータ

+ +
+
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
+
ImageBitmap が抽出される矩形の参照点の x 座標。
+
sy
+
ImageBitmap が抽出される矩形の参照点の y 座標。
+
sw
+
ImageBitmap が抽出される矩形の幅。この値は負の値にすることができます。
+
sh
+
ImageBitmap が抽出される矩形の高さ。この値は負の値にすることができます。
+
options {{optional_inline}}
+
画像の抽出のためのオプションを設定するオブジェクト。利用可能なオプションは以下の通りです。 +
    +
  • imageOrientation: 画像をそのまま表示するか、垂直方向に反転させて表示するかを指定します。none (デフォルト) または flipY のいずれかを指定します
  • +
  • premultiplyAlpha: ビットマップのカラーチャンネルをアルファチャンネルで前置増幅するかどうかを指定します。nonepremultiplydefault (デフォルト) のいずれかです
  • +
  • colorSpaceConversion: 画像を色空間変換でデコードするかどうかを指定します。none または default (デフォルト) のいずれかを指定します。値 default は、実装固有の動作を使用することを示します
  • +
  • resizeWidth: 出力幅を示す long 整数
  • +
  • resizeHeight: 出力の高さを示す long 整数
  • +
  • resizeQuality: 出力寸法に合わせて入力のサイズを変更するために使用するアルゴリズムを指定します。pixelatedlow (デフォルト)、mediumhighのいずれかです
  • +
+
+
+ +

戻り値

+ +

与えられた矩形のビットマップデータを含む{{domxref("ImageBitmap")}} オブジェクトに解決する{{domxref("Promise")}} を返します。

+ +

+ +

スプライトシートからのスプライト作成

+ +

この例では、スプライトシートをロードし、個々のスプライトを抽出し、各スプライトをキャンバスにレンダリングします。スプライトシートとは、複数の小さな画像を含む画像で、それぞれを個別にレンダリングできるようにしたいものです。

+ +
var canvas = document.getElementById('myCanvas'),
+ctx = canvas.getContext('2d'),
+image = new Image();
+
+// スプライトシートがロードされるのを待ちます
+image.onload = function() {
+  Promise.all([
+    // スプライトシートから2つのスプライトを切り取ります
+    createImageBitmap(image, 0, 0, 32, 32),
+    createImageBitmap(image, 32, 0, 32, 32)
+  ]).then(function(sprites) {
+    // 各スプライトをキャンバスに描きます
+    ctx.drawImage(sprites[0], 0, 0);
+    ctx.drawImage(sprites[1], 32, 32);
+  });
+}
+
+// 画像ファイルからスプライトシートを読み込みます
+image.src = 'sprites.png';
+
+ +

仕様

+ + + + + + + + + + + + + + +
仕様書ステータスコメント
{{SpecName('HTML WHATWG', "webappapis.html#dom-createimagebitmap", "createImageBitmap")}}{{Spec2('HTML WHATWG')}}
+ +

ブラウザの互換性

+ +

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

+ +

あわせて参照

+ + diff --git a/files/ja/web/api/fetch/index.html b/files/ja/web/api/fetch/index.html new file mode 100644 index 0000000000..79024057be --- /dev/null +++ b/files/ja/web/api/fetch/index.html @@ -0,0 +1,192 @@ +--- +title: WindowOrWorkerGlobalScope.fetch() +slug: Web/API/fetch +tags: + - API + - Experimental + - Fetch + - Fetch API + - GlobalFetch + - Method + - Reference + - WindowOrWorkerGlobalScope + - request + - メソッド +translation_of: Web/API/WindowOrWorkerGlobalScope/fetch +original_slug: Web/API/WindowOrWorkerGlobalScope/fetch +--- +

{{APIRef("Fetch API")}}

+ +

fetch() は {{domxref("WindowOrWorkerGlobalScope")}} ミックスインのメソッドで、ネットワークからリソースを取得するプロセスを開始し、レスポンスが利用できるようになったら満足するプロミスを返します。このプロミスはリクエストに対するレスポンスを表す {{domxref("Response")}} で解決します。プロミスは HTTP エラーでは拒否されず、ネットワークエラーでのみ拒否されます。 HTTP エラーをチェックするには、 then ハンドラーを使用する必要があります。

+ +

WindowOrWorkerGlobalScope は {{domxref("Window")}} と {{domxref("WorkerGlobalScope")}} の両方で実装されています。これはつまり fetch() メソッドはあなたがリソースを取得したいと思うような大部分コンテキストで使用可能ということです。

+ +

{{domxref("WindowOrWorkerGlobalScope.fetch","fetch()")}} のプロミスはネットワークエラーが発生した場合 (すなわち普通はパーミッション問題などがあったとき) のみ拒否されます。 {{domxref("WindowOrWorkerGlobalScope.fetch","fetch()")}} のプロミスは HTTP エラー (404 など) では拒否されません。代わりに、 then() ハンドラーで {{domxref("Response.ok")}} や {{domxref("Response.status")}} プロパティをチェックする必要があります。

+ +

fetch() メソッドは取得するリソースのディレクティブではなく Content Security Policyconnect-src ディレクティブによって制御されます。

+ +
+

: fetch() メソッドの引数は {{domxref("Request.Request","Request()")}} コンストラクターと全く同じです。

+
+ +

構文

+ +
const fetchResponsePromise = fetch(resource [, init])
+
+ +

引数

+ +
+
resource
+
取得したいリソースを定義します。以下の 2 つが使用出来ます。 +
    +
  • 取得したいリソースの直接の URL を含む {{domxref("USVString")}}。ブラウザーによってはスキームとして blob:data: を受け入れます。
  • +
  • {{domxref("Request")}} オブジェクト。
  • +
+
+
init {{optional_inline}}
+
+

リクエストに適用したいカスタム設定を含むオブジェクト。可能なオプションは以下の通りです。

+ +
+
method
+
リクエストするメソッド、GETPOST など。なお、 {{httpheader("Origin")}} ヘッダーは {{HTTPMethod("HEAD")}} または {{HTTPMethod("GET")}} メソッドの読み取りリクエストでは設定されません。
+ (この動作は Firefox 65 で修正されました — {{bug(1508661)}} を参照)
+
headers
+
リクエストに追加したいヘッダーで、{{domxref("Headers")}} オブジェクトか {{domxref("ByteString")}} 値を持つオブジェクトリテラルで指定してください。なお、一部の名前は禁止されています
+
body
+
リクエストに追加したい本文です。これには {{domxref("Blob")}}, {{domxref("BufferSource")}}, {{domxref("FormData")}}, {{domxref("URLSearchParams")}}, {{domxref("USVString")}}, {{domxref("ReadableStream")}} オブジェクトなどが使用できます。メソッドが GETHEAD の場合使用できないので注意してください。
+
mode
+
リクエストで使いたいモードです。例: cors, no-cors, same-origin
+
credentials
+
リクエストに使用したいリクエスト認証情報、 omit, same-origin, include です。現在のドメインの Cookie を自動で送るためにはこのオプションを指定する必要があります。 Chrome 50 から、このプロパティは{{domxref("FederatedCredential")}} インスタンスや {{domxref("PasswordCredential")}} インスタンスを受け付けるようになりました。
+
cache
+
使用したいリクエストのキャッシュモードです。
+
redirect
+
使用するリダイレクトモードです。 follow (自動でリダイレクトに従う)、 error (リダイレクトが起こった場合エラーを伴って中止する)、 manual (手動でリダイレクトを処理する)。Chrome の既定値は follow です (バージョン 47 より前の既定値は manual でした)。
+
referrer
+
{{domxref("USVString")}} でリクエストのリファラーを指定します。これは同じオリジンの URL、 about:client、空文字列のいずれかを取ることができます。
+
referrerPolicy
+
リクエストで使用するリファラーポリシーを指定します。使用可能な値は、 no-referrer, no-referrer-when-downgrade, same-origin, origin, strict-origin, origin-when-cross-origin, strict-origin-when-cross-origin, or unsafe-url のいずれかです。
+
integrity
+
リソースに subresource integrity 値を含ませることが出来ます (例:sha256-BpfBw7ivV8q2jLiT13fxDYAe2tJllusRSZ273h2nFSE=)。
+
keepalive
+
keepalive オプションはページより長生きするリクエストを許可するのに使われます。keepalive フラグつきの Fetch は{{domxref("Navigator.sendBeacon()")}} API の置き換えです。
+
signal
+
{{domxref("AbortSignal")}} オブジェクトのインスタンスです。つまり {{domxref("AbortController")}} 経由で fetch リクエストと通信したり望む場合には中止したりできます。
+
+
+
+ +

返値

+ +

{{domxref("Promise")}} で、 {{domxref("Response")}} オブジェクトに解決します。

+ +

例外

+ +
+
AbortError
+
{{domxref("AbortController")}} メソッドまたは {{domxref("AbortController.abort", "abort()")}} メソッドの呼び出しによりリクエストが中止された。
+
TypeError
+
指定された URL がユーザー認証情報を含んでいる。この情報は {{HTTPHeader("Authorization")}} ヘッダーを用いて提供するべきです。
+
+ +

+ +

Fetch Request example リポジトリ (デモ: Fetch Request live) では {{domxref("Request")}} オブジェクトを関連するコンストラクターを使って作成しています。その後 fetch() を呼んで取得しています。画像を fetch している時から適切な MIME タイプを与えるために response の {{domxref("Body.blob")}} を実行し、適切に処理されます。そして ObjectURL を作成し {{htmlelement("img")}} 要素に追加して表示させています。

+ +
const myImage = document.querySelector('img');
+
+let myRequest = new Request('flowers.jpg');
+
+fetch(myRequest)
+.then(function(response) {
+  if (!response.ok) {
+    throw new Error(`HTTP error! status: ${response.status}`);
+  }
+  return response.blob();
+})
+.then(function(response) {
+  let objectURL = URL.createObjectURL(response);
+  myImage.src = objectURL;
+});
+ +

Fetch with init then Request example リポジトリ (デモ: Fetch Request init live) では上記の内容に加えて、fetch() を呼び出すとき、初期化オブジェクト init を渡しています。

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

同様に init オブジェクトを Request コンストラクターに渡しても、同じ効果が得られます。

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

initinit としてオブジェクトリテラルを使用することもできます。

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

仕様書

+ + + + + + + + + + + + + + + + + + + + + + + + + + +
仕様書状態備考
{{SpecName('Fetch','#fetch-method','fetch()')}}{{Spec2('Fetch')}}最新の仕様では WindowOrWorkerGlobalScope の中で部分的に定義。
{{SpecName('Fetch','#dom-global-fetch','fetch()')}}{{Spec2('Fetch')}}初回定義
{{SpecName('Credential Management')}}{{Spec2('Credential Management')}}{{domxref("FederatedCredential")}} または {{domxref("PasswordCredential")}} のインスタンスを init.credentials の値として追加。
+ +

ブラウザーの互換性

+ +

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

+ +

関連情報

+ + diff --git a/files/ja/web/api/indexeddb/index.html b/files/ja/web/api/indexeddb/index.html new file mode 100644 index 0000000000..bdf8532b6a --- /dev/null +++ b/files/ja/web/api/indexeddb/index.html @@ -0,0 +1,72 @@ +--- +title: WindowOrWorkerGlobalScope.indexedDB +slug: Web/API/indexedDB +tags: + - API + - Database + - IndexedDB + - Property + - Reference + - Storage +translation_of: Web/API/WindowOrWorkerGlobalScope/indexedDB +original_slug: Web/API/WindowOrWorkerGlobalScope/indexedDB +--- +

{{ APIRef() }}

+ +

{{domxref("WindowOrWorkerGlobalScope")}} ミックスインの indexedDB 読み取り専用プロパティは、アプリケーションが indexed データベースのキャパビリティに非同期でアクセスするための機構を提供します。

+ +

構文

+ +
var IDBFactory = self.indexedDB;
+ +

+ +

{{domxref("IDBFactory")}} オブジェクト。

+ +

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

仕様

+ + + + + + + + + + + + + + + + + + + +
仕様書策定状況備考
{{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')}}初期定義。
+ +

ブラウザーの実装状況

+ +

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

+ +

関連情報

+ + diff --git a/files/ja/web/api/issecurecontext/index.html b/files/ja/web/api/issecurecontext/index.html new file mode 100644 index 0000000000..877738b41b --- /dev/null +++ b/files/ja/web/api/issecurecontext/index.html @@ -0,0 +1,57 @@ +--- +title: WindowOrWorkerGlobalScope.isSecureContext +slug: Web/API/isSecureContext +tags: + - API + - DOM + - Window + - WindowOrWorkerGlobalContext + - Workers + - isSecureContext + - ウェブ + - プロパティ + - リファレンス +translation_of: Web/API/WindowOrWorkerGlobalScope/isSecureContext +original_slug: Web/API/WindowOrWorkerGlobalScope/isSecureContext +--- +

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

+ +

{{domxref("WindowOrWorkerGlobalScope")}} インターフェイスの読み取り専用 isSecureContext プロパティは、現在のコンテキストが安全(true)かそうではない(false)を示すブール値を返します。

+ +

構文

+ +
var isItSecure = self.isSecureContext; // or just isSecureContext
+
+ +

+ +

{{domxref("Boolean")}}.

+ +

仕様

+ + + + + + + + + + + + + + +
仕様ステータスコメント
{{SpecName('Secure Contexts', '#dom-windoworworkerglobalscope-issecurecontext', 'WindowOrWorkerGlobalScope.isSecureContext')}}{{Spec2('Secure Contexts')}}初期定義。
+ +

ブラウザ互換性

+ + + +

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

+ +

参照

+ + diff --git a/files/ja/web/api/origin/index.html b/files/ja/web/api/origin/index.html new file mode 100644 index 0000000000..cf78260061 --- /dev/null +++ b/files/ja/web/api/origin/index.html @@ -0,0 +1,59 @@ +--- +title: WindowOrWorkerGlobalScope.origin +slug: Web/API/origin +tags: + - API + - DOM + - Window + - WindowOrWorkerGlobalScope + - Worker + - ウェブ + - プロパティ +translation_of: Web/API/WindowOrWorkerGlobalScope/origin +original_slug: Web/API/WindowOrWorkerGlobalScope/origin +--- +

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

+ +

{{domxref("WindowOrWorkerGlobalScope")}} インターフェイスの読み取り専用プロパティ origin は、グローバルスコープの文字列としてシリアライズされた origin を返します。

+ +

構文

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

+ +

{{domxref("USVString")}}.

+ +

+ +

worker script 内から実行される以下のスニペットは、メッセージを受け取る度にワーカーのグローバルスコープの origin をコンソールに記録します。

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

もし origin が scheme/host/port tuple出ない場合 (あなたがローカルで実行しようとしている、言い換えると file:// というURLの場合)、 origin は "null" という文字列を返すでしょう。

+ +

仕様

+ + + + + + + + + + + + + + +
仕様ステータスコメント
{{SpecName('HTML WHATWG', 'webappapis.html#dom-origin', 'WindowOrWorkerGlobalScope.origin')}}{{Spec2('HTML WHATWG')}}初期定義。
+ +

ブラウザ互換性

+ + + +

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

diff --git a/files/ja/web/api/setinterval/index.html b/files/ja/web/api/setinterval/index.html new file mode 100644 index 0000000000..f6f721580b --- /dev/null +++ b/files/ja/web/api/setinterval/index.html @@ -0,0 +1,636 @@ +--- +title: WindowOrWorkerGlobalScope.setInterval() +slug: Web/API/setInterval +tags: + - API + - DOM + - Gecko + - Intervals + - JavaScript timers + - MakeBrowserAgnostic + - Method + - NeedsMarkupWork + - Timers + - WindowOrWorkerGlobalScope + - setInterval +translation_of: Web/API/WindowOrWorkerGlobalScope/setInterval +original_slug: Web/API/WindowOrWorkerGlobalScope/setInterval +--- +
{{APIRef("HTML DOM")}}
+ +

{{domxref("WindowOrWorkerGlobalScope")}} ミックスインの setInterval() メソッドは、一定の遅延間隔を置いて関数やコードスニペットを繰り返し呼び出します。これは、インターバルを一意に識別する interval ID を返します。よって {{domxref("WindowOrWorkerGlobalScope.clearInterval", "clearInterval()")}} を呼び出して、後でインターバルを削除できます。このメソッドは {{domxref("Window")}} および {{domxref("Worker")}} インターフェイスで提供します。

+ +

構文

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

引数

+ +
+
func
+
ミリ秒単位の delay が経過するたびに実行する {{jsxref("function", "関数")}} です。関数には引数が渡されず、また戻り値を想定していません。
+
code
+
関数の代わりに文字列を含める構文も許容されており、ミリ秒単位の delay が経過するたびに文字列をコンパイルして実行します。{{jsxref("eval", "eval()")}} の使用にリスクがあるのと同じ理由で、この構文は 推奨しません
+
delay
+
指定した関数またはコードを実行する前にタイマーが待つべき時間をミリ秒 (1/1000 秒) 単位で指定します。引数が 10 より小さい場合は、10 を使用します。実際の遅延が長くなることがあります。例えば {{SectionOnPage("/ja/docs/Web/API/WindowOrWorkerGlobalScope/setTimeout", "遅延が指定値より長い理由")}} をご覧ください。
+
param1, ..., paramN {{optional_inline}}
+
タイマーが満了したときに、func で指定した関数に渡す追加の引数です。
+
+ +
+

注記: Internet Explorer 9 およびそれ以前のバージョンでは、最初の構文で setInterval() に渡す追加の引数は動作しないことに注意してください。同様の機能を実現させるには、ポリフィルを使用してください。(コールバックの引数 を参照)。

+
+ +

戻り値

+ +

戻り値 intervalID は、setInterval() を呼び出して作成したタイマーを識別する、0 ではない正の整数値です。この値は、インターバルをキャンセルするために {{domxref("WindowOrWorkerGlobalScope.clearInterval()")}} へ渡すことができます。

+ +

setInterval() と {{domxref("WindowOrWorkerGlobalScope.setTimeout", "setTimeout()")}} は同じ ID プールを共有しており、さらに clearInterval() と {{domxref("WindowOrWorkerGlobalScope.clearTimeout", "clearTimeout()")}} は技術的に入れ替えて使用できることを意識すると役に立つでしょう。ただし明快さのために、コードを整備するときは混乱を避けるため、常に一致させるようにするべきです。

+ +
注記: 引数 delay は、符号付き 32 ビット整数に変換されます。IDL における符号付き整数の定義によって、delay は事実上 2147483647ms に制限されます。
+ +

+ +

例 1: 基本的な構文

+ +

以下の例は、setInterval() の基本的な構文を示します。

+ +
var intervalID = window.setInterval(myCallback, 500);
+
+function myCallback() {
+  // Your code here
+}
+
+ +

例 2: 2 つの色を切り替える

+ +

以下の例は停止ボタンを押すまで、1 秒おきに flashtext() 関数を呼び出します。

+ +
<!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>
+<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>
+ +

View this demo in action. See also: 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[, param1, param2, ...]);
+|*|  var timeoutID = window.setTimeout(code, delay);
+|*|  var intervalID = window.setInterval(func, delay[, param1, param2, ...]);
+|*|  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);
+ +

さらに、関数の bind を使用する方法もあります。例えば:

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

{{h3_gecko_minversion("非アクティブなタブ", "5.0")}}

+ +

Gecko 5.0 {{geckoRelease("5.0")}} より非アクティブなタブでは、1 秒あたり 1 回を超えて実行しないようにインターバルを制限します。

+ +

"this" 問題

+ +

setInterval() (もっと言うと他のどんな関数でも) にメソッドを渡すと、間違った this の値で呼び出されることがあります。この問題は JavaScript リファレンス で詳しく説明されています。

+ +

説明

+ +

setInterval() によって実行されるコードは、setInterval が呼び出された関数とは別の実行コンテキスト内で実行されます。その結果、呼び出された関数の this キーワードは window (または global) オブジェクトに設定されます。これは setTimeout を呼び出した関数の this の値とは異なります。以下の例をご覧ください (ここでは setInterval() ではなく setTimeout() を使用していますが、どちらのタイマーでも問題は同じです):

+ +
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
+
+ +

この例でわかるとおり、旧来の JavaScript でコールバック関数に this オブジェクトを渡す方法はありません。

+ +

考えられる解決策

+ +

"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);
+};
+ +
これら 2 つの置き換えにより、IE のタイマーで HTML5 標準の、コールバック関数に任意の引数を渡すことも可能になります。よって、標準仕様に準拠しない ポリフィルとしても使用できます。標準仕様に準拠するポリフィルについては、コールバックの引数 をご覧ください。
+ +

新機能のテスト:

+ +
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
+
+ +

この他に this 問題のより複雑な解決策として、後述するフレームワーク もあります。

+ +
JavaScript 1.8.5 で、関数のすべての呼び出しで this として使用する値を設定できる、Function.prototype.bind() メソッドを導入しました。これにより、関数を呼び出したコンテキストに応じて this がどのようになるかが明確にならない問題を簡単に回避できます。また、ES2015 では アロー関数 をサポートして、字句 this と組み合わせると myArray の内部では setInterval( () => this.myMethod) と記述できます。
+ +

MiniDaemon: タイマー管理フレームワーク

+ +

多くのタイマーが必要なページでは、実行中のタイマーのイベントをすべて追跡し続けることが困難な場合があります。この問題の解決策のひとつが、オブジェクト内のタイマーの状態に関する情報を保存することです。以下のコードは、そのような抽象化の最小限の例です。コンストラクターは、クロージャの使用を明示的に避けるアーキテクチャになっています。また、this オブジェクトをコールバック関数に渡す代替手段も提供します (詳しくは "this" 問題 をご覧ください)。以下のコードは GitHub でも入手できます

+ +
より複雑ですがモジュール化したもの (Daemon) については、JavaScript Daemons Management をご覧ください。このより複雑なバージョンは、Daemon コンストラクター用の大規模でスケーラブルなメソッドのコレクションに過ぎません。しかし Daemon コンストラクター自体は、daemon のインスタンス化の間に宣言可能な init および onstart 関数のサポートを追加した MiniDaemon のクローンに過ぎません。よって MiniDaemon フレームワークは、シンプルなアニメーションのために推奨する方法であり続けます。これは、メソッドのコレクションがない Daemon が本質的に MiniDaemon のクローンであるためです。
+ +

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 は、引数をコールバック関数に渡します。この機能をネイティブにサポートしないブラウザーで動作させたい場合は、ここで提案したメソッドのいずれかを使用してください。
+ +

構文

+ +

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

+ +

説明

+ +

アニメーションで必要なすべての情報 (this オブジェクト、コールバック関数、長さ、フレームレート) を持つ JavaScript Object を返します。

+ +

引数

+ +
+
thisObject
+
コールバック関数が呼び出された this オブジェクト。object または null を使用できます。
+
callback
+
繰り返し実行する関数。これは 3 個の引数を伴って呼び出されますindex (反復処理の、毎回の処理のインデックス)、length (daemon に割り当てられた総実行回数。有限の数値または Infinity を指定できます)、backwards (index を加算するか減算するかを示す論理値)。これは callback.call(thisObject, index, length, backwards) のようなものです。コールバック関数が false 値を返す場合は、daemon が一時停止しています
+
rate (省略可能)
+
毎回の実行の時間間隔 (ミリ秒単位の数値)。デフォルト値は 100 です。
+
length (省略可能)
+
総実行回数。正の整数または Infinity を使用できます。デフォルト値は Infinity です。
+
+ +

MiniDaemon インスタンスのプロパティ

+ +
+
myDaemon.owner
+
daemon が実行される this オブジェクト (読み書き可能)。object または null を使用できます。
+
myDaemon.task
+
繰り返し実行する関数 (読み書き可能)。これは 3 個の引数を伴って呼び出されます。index (反復処理の、毎回の処理のインデックス)、length (daemon に割り当てられた総実行回数。有限の数値または Infinity を指定できます)、backwards (index 減算するか否かを示す論理値)。myDaemon.task の関数が false 値を返す場合は、daemon が一時停止しています。
+
myDaemon.rate
+
毎回の実行の時間間隔 (ミリ秒単位の数値、読み書き可能)。
+
myDaemon.length
+
総実行回数。正の整数または Infinity を使用できます (読み書き可能)。
+
+ +

MiniDaemon インスタンスのメソッド

+ +
+
myDaemon.isAtEnd()
+
daemon が開始/終了状態であるか否かを示す論理値を返します。
+
myDaemon.synchronize()
+
開始した daemon のタイマーと、daemon の実行時間を同期します。
+
myDaemon.pause()
+
daemon を一時停止します。
+
myDaemon.start([reverse])
+
daemon を前方 (毎回実行するたびに index が増加) または後方 (index が減少) に開始します。
+
+ +

MiniDaemon グローバルオブジェクトのメソッド

+ +
+
MiniDaemon.forceCall(minidaemon)
+
終端に達しているか否かの事実にかかわらず、minidaemon.task の関数へのひとつのコールバックを強制します。どの場合も、内部の INDEX プロパティは (実際の実行方向に応じて) 増加または減少します。
+
+ +

使用例

+ +

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>
+ +

実際の動作例を見る

+ +

注記

+ +

setInterval() 関数は一般に、アニメーションのように何度も実行される関数に遅延をセットするのに使われます。

+ +

{{domxref("WindowOrWorkerGlobalScope.clearInterval()")}} を使ってインターバルをキャンセルすることができます。

+ +

指定時間後に 一度 だけ関数を呼び出したい場合には、{{domxref("WindowOrWorkerGlobalScope.setTimeout()")}} を使います。

+ +

実行時間をインターバルより確実に短くする

+ +

ロジックの実行時間がインターバル時間より長くなる可能性がある場合は、{{domxref("WindowOrWorkerGlobalScope.setTimeout")}} を使用して名前付き関数を再帰的に呼び出すことを推奨します。例えば 5 秒おきにリモートサーバーへ接続するために setInterval を使用するとき、ネットワークの遅延やサーバーの不応答などさまざまな問題で、割り当てられた時間内にリクエストが完了しない可能性があります。そのため、必ずしも順番どおりには返らない XHR リクエストがキュー内にあることに気づくかもしれません。

+ +

この場合は、再帰的な setTimeout() のパターンを推奨します:

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

このコードスニペットでは、名前付き関数 loop() を宣言して直ちに実行します。loop() はロジックが完全に実行された後に、内部の setTimeout() によって再帰呼び出しされます。このパターンは一定の間隔で呼び出すことが保証されませんが、再帰呼び出しの前に前の実行が完了することが保証されます。

+ +

インターバルを抑制する

+ +

Firefox で setInterval() は、{{domxref("WindowOrWorkerGlobalScope.setTimeout","setTimeout()")}} と同様に、インターバルが制限されます。遅延が指定値より長い理由 をご覧ください。

+ +

仕様

+ + + + + + + + + + + + + + + + + + + +
仕様書策定状況コメント
{{SpecName('HTML WHATWG', 'webappapis.html#dom-setinterval', 'WindowOrWorkerGlobalScope.setInterval()')}}{{Spec2("HTML WHATWG")}}最新の仕様で、メソッドを WindowOrWorkerGlobalScope ミックスインに移動。
{{SpecName("HTML WHATWG", "webappapis.html#dom-setinterval", "WindowTimers.setInterval()")}}{{Spec2("HTML WHATWG")}}最初期の定義 (DOM Level 0)
+ +

ブラウザー実装状況

+ +
+ + +

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

+
+ +

関連情報

+ + diff --git a/files/ja/web/api/settimeout/index.html b/files/ja/web/api/settimeout/index.html new file mode 100644 index 0000000000..865c4679a6 --- /dev/null +++ b/files/ja/web/api/settimeout/index.html @@ -0,0 +1,420 @@ +--- +title: WindowOrWorkerGlobalScope.setTimeout() +slug: Web/API/setTimeout +tags: + - API + - HTML DOM + - Intervals + - JavaScript timers + - MakeBrowserAgnostic + - Method + - NeedsCompatTable + - NeedsMarkupWork + - NeedsUpdate + - Reference + - Timers + - WindowOrWorkerGlobalScope + - setTimeout +translation_of: Web/API/WindowOrWorkerGlobalScope/setTimeout +original_slug: Web/API/WindowOrWorkerGlobalScope/setTimeout +--- +
{{APIRef("HTML DOM")}}
+ +

setTimeout() は {{domxref("WindowOrWorkerGlobalScope")}} ミックスインのメソッド (および Window.setTimeout() の後継) で、時間切れになると関数または指定されたコードの断片を実行するタイマーを設定します。

+ +

構文

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

引数

+ +
+
function
+
タイマーが満了した後に実行したい {{jsxref("function", "関数")}}。
+
code
+
関数の代わりに文字列を含める代替構文も許容されており、タイマーが満了したときに文字列をコンパイルして実行します。 {{jsxref("Global_Objects/eval", "eval()")}} の使用にリスクがあるのと同じ理由で、この構文は推奨しません
+
delay {{optional_inline}}
+
指定した関数やコードを実行する前に待つタイマーの時間をミリ秒 (1/1000 秒) 単位で指定します。この引数を省略すると値 0 を使用しますので "直ちに" 実行する、より正確に言えばできるだけ早く実行することを意味します。どちらの場合も、実際の遅延が想定より長くなることがあります。後述する {{anch("Reasons for delays longer than specified", "遅延が指定値より長い理由")}} をご覧ください。
+
arg1, ..., argN {{optional_inline}}
+
タイマーが満了したときに、 function で指定された関数に渡す追加の引数です。
+
+ +
+

: Internet Explorer 9 およびそれ以前のバージョンでは、最初の構文で関数に渡す追加の引数は動作しないことに注意してください。同様の機能を実現させるには、ポリフィルを使用してください。({{anch("Polyfill", "ポリフィル")}} を参照)。

+
+ +

返値

+ +

返される timeoutID は正の整数値で、 setTimeout() を呼び出して作成したタイマーを識別します。この値を {{domxref("WindowOrWorkerGlobalScope.clearTimeout","clearTimeout()")}} へ渡すことで、タイムアウトを取り消すことができます。

+ +

setTimeout() と {{domxref("WindowOrWorkerGlobalScope.setInterval", "setInterval()")}} は同じ ID プールを共有しており、さらに clearTimeout() と {{domxref("WindowOrWorkerGlobalScope.clearInterval", "clearInterval()")}} は技術的に入れ替えて使用できることを意識すると役に立つかもしれません。ただし明確さのために、コードを整備するときは混乱を避けるため、常に一致させるようにするべきです。

+ +

同じオブジェクト (ウィンドウやワーカー) では、後に setTimeout()setInterval() を呼び出しても タイムアウト ID を再使用しないことが保証されています。ただし、別なオブジェクトでは別の ID プールを使用します。

+ +

+ +

以下の例はウェブページに 2 つのシンプルなボタンを置いており、setTimeout() および clearTimeout() のルーチンを実行します。1 番目のボタンを押下すると 2 秒後にアラートダイアログを呼び出すタイムアウトを設定して、clearTimeout() で使用するタイムアウト ID を保存します。2 番目のボタンを押下すると、このタイムアウトをキャンセルできます。

+ +

HTML

+ +
<p>Live Example</p>
+<button onclick="delayedAlert();">2秒後にアラートボックスを表示する</button>
+<p></p>
+<button onclick="clearAlert();">アラートを事前にキャンセルする</button>
+
+ +

JavaScript

+ +
var timeoutID;
+
+function delayedAlert() {
+  timeoutID = window.setTimeout(window.alert, 2*1000, '本当に遅い!');
+}
+
+function clearAlert() {
+  window.clearTimeout(timeoutID);
+}
+
+ +

結果

+ +

{{EmbedLiveSample('Example')}}

+ +

clearTimeout() の例 もご覧ください。

+ +

ポリフィル

+ +

コールバック関数に 1 つ以上の引数を渡す必要があるが、setTimeout()setInterval() を使用して追加の引数を渡す機能に対応していないブラウザー (例えば Internet Explorer 9 以前) で動作しなければならない場合は、HTML5 標準の引数渡し機能を可能にする以下のポリフィルを追加するとよいでしょう。このコードをスクリプトの先頭に追加してください。

+ +
/*\
+|*|
+|*|  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[, arg1, arg2, ...]);
+|*|  var timeoutID = window.setTimeout(code, delay);
+|*|  var intervalID = window.setInterval(func, delay[, arg1, arg2, ...]);
+|*|  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 限定の修正

+ +

IE 9 およびそれ以前を含む、他のすべてのモバイルブラウザーやデスクトップブラウザーで完全に目立たない修正が必要である場合は、以下の 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);
+
+ +

さらに、関数の bind を使用する方法もあります。例:

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

"this" 問題

+ +

setTimeout() にメソッド (そういうことならほかの関数も) を渡すとき、コードが実行される際の this の値が想定とは異なるかもしれません。この問題は JavaScript リファレンス でより詳細に説明されています。

+ +

説明

+ +

setTimeout() によって実行されるコードは、 setTimeout が呼び出された関数とは別の実行コンテキスト内から呼び出されます。呼び出された関数に this キーワードを設定する通常の規則を適用して、呼び出しあるいは bindthis を設定しなければ、非 strict モードでは global (または window)、strict モードでは undefined になります。これは、setTimeout が呼び出された関数の this 値と同じにはなりません。

+ +
+

注: setTimeout コールバックの既定の this の値は、厳格モードであっても undefined ではなく、 window オブジェクトです。

+
+ +

以下の例をご覧ください。

+ +
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"
+ +

myMethod を呼び出したときに、呼び出しによって thismyArray に設定されますので、関数内で this[sProperty]myArray[sProperty] と等価です。しかし、以下のコードでは動作が異なります。

+ +
setTimeout(myArray.myMethod, 1.0*1000); // 1秒後に "[object Window]" と表示
+setTimeout(myArray.myMethod, 1.5*1000, '1'); // 1.5秒後に "undefined" と表示
+ +

myArray.myMethod 関数を setTimeout に渡しており、関数が呼び出されると this が前のように設定されず、既定値の window オブジェクトになります。Array の forEach や reduce などのメソッドにあるような、thisArg を setTimeout に渡すオプションもありません。また以下のように、this を設定するために call を使用する方法も動作しません。

+ +
setTimeout.call(myArray, myArray.myMethod, 2.0*1000); // error: "NS_ERROR_XPC_BAD_OP_ON_WN_PROTO: Illegal operation on WrappedNative prototype object"
+setTimeout.call(myArray, myArray.myMethod, 2.5*1000, 2); // same error
+
+ +

考えられる解決策

+ +

この問題の一般的な解決策は、this に必要な値を設定するラッパー関数を使用することです:

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

代わりにアロー関数も使用できます。

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

他に考えられる "this" 問題の解決策として、本来の setTimeout() および setInterval() グローバル関数を、this オブジェクトを渡せるようにして、コールバックで Function.prototype.call を使用して設定するように置き換える方法があります。例えば:

+ +
// Enable setting 'this' in 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);
+};
+ +
: これら 2 つの置き換えにより、IE のタイマーで HTML5 標準の、コールバック関数に任意の引数を渡すことも可能になります。よって、ポリフィルとしても使用できます。Callback arguments の節をご覧ください。
+ +

新機能のテスト:

+ +
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, 2.0*1000); // prints "zero,one,two" after 2 seconds
+setTimeout.call(myArray, myArray.myMethod, 2.5*1000, 2); // prints "two" after 2.5 seconds
+
+ +
: JavaScript 1.8.5 で、関数のすべての呼び出しに対して this の値を設定する Function.prototype.bind() メソッドを導入しました。これにより、コールバックで this の値を設定するためにラッパー関数を使用しなければならない状況を回避できます。
+ +

bind() の使用例:

+ +
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, 1.0*1000); // still prints "zero,one,two" after 1 second because of the binding
+setTimeout(myBoundMethod, 1.5*1000, "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()")}} がコールバックのネスト (ネストの深さが少なくとも数段階ある) によって連続的に呼び出された、あるいは連続的なインターバルが数回発生した後に呼び出されたときに、少なくとも 4 ミリ秒ごとに呼び出されるように制限をかけます。例えば:

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

Chrome および Firefox では、5 回目の連続的なコールバックの呼び出しで制限をかけます。また Safar は 6 回目、Edge は 3 回目で制限をかけます。Gecko は バージョン 56 で、setInterval() で制限を始めました (後述のとおり setTimeout() は以前から行っていました)。

+ +

歴史的に 一部のブラウザー (例えば Firefox) は、あらゆる場所から呼び出された setInterval()、あるいはネストの深さが少なくとも数段階ある setTimeout() が呼び出されたときの制限を、若干異なる動作で実装しています。。

+ +

0 ms タイマーをモダンブラウザーで実装するには、ここで説明されている {{domxref("window.postMessage()")}} を利用できます。

+ +
+

: 最小遅延である DOM_MIN_TIMEOUT_VALUE は 4 ms (Firefox の dom.min_timeout_value の設定に保存されています) であり、DOM_CLAMP_TIMEOUT_NESTING_LEVEL は 5 です。

+
+ +
+

: 4 ms は HTML5 の仕様で標準化されています。 そして、2010 年以降にリリースされたブラウザー間で一貫しています。{{geckoRelease("5.0")}} 以前では、ネストされた setTimeout の最小値は 10 ms でした。

+
+ +

非アクティブタブのタイムアウトは 1000 ms 以上に制限される

+ +

バックグラウンドのタブによる負荷 (およびバッテリー消費) を軽減するため、アクティブ状態でないタブでのタイマーの呼び出しは、1 秒 (1,000 ms) あたり 1 回までとなります。

+ +

Firefox はこの動作をバージョン 5 ({{bug(633421)}} を参照。1000 ms の定数は設定項目 dom.min_background_timeout_value で変更できます) から、Chrome はこの動作をバージョン 11 (crbug.com/66078) から実装しています。

+ +

Android 版 Firefox は {{bug(736602)}} によって、 Firefox 14 からバックグラウンドタブで 15 分のタイムアウト値を使用しており、またバックグラウンドタブを完全にアンロードすることもできます。

+ +
+

Firefox 50 では、 Web Audio API の {{domxref("AudioContext")}} が音声を再生中であればバックグラウンドタブの制限を行いません。さらに Firefox 51 では、音声を再生していなくても {{domxref("AudioContext")}} を提供していれば、バックグラウンドタブの制限を行わないように改良しました。これによりタブがバックグラウンドであるときに、楽譜を基に音楽を再生するアプリで拍子が合わない、あるいは音楽が正しく同期しないといった問題が解決します。

+
+ +

トラッキングスクリプトのタイムアウトを制限する

+ +

Firefox 55 より、トラッキングスクリプト (例えば Google Analytics や、TP リスト によって Firefox がトラッキングスクリプトであると認識するスクリプトの URL) にさらなる制限を課します。フォアグラウンドで実行しているとき、最小遅延の制限は 4ms のままです。しかしバックグラウンドのタブでは、最小遅延を 10,000ms または 10 秒に制限します。これはドキュメントが最初に読み込まれてから 30 秒後に発効します。

+ +

この動作を制御する設定項目は以下のとおりです。

+ + + +

タイムアウトの遅延

+ +

前出の "制限" に加えて、ページ内 (またはOSやブラウザー自身) の他のタスクの処理に時間がかかると、タイムアウトは遅れます。注目すべき重要なケースとして、setTimeout() を呼び出したスレッドが終了するまで関数やコードスニペットを実行できないことが挙げられます。例えば:

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

このコードは、コンソールへ以下のように出力します。

+ +
After setTimeout
+foo has been called
+ +

これは setTimeout を遅延 0 で呼び出したとしても、直ちに実行するのではなくキューに載せて、次の機会に実行するようスケジューリングされるためです。現在実行中のコードはキューにある関数を実行する前に完了しなければならず、このために実行結果の順序が想定どおりにならない場合があります。

+ +

WebExtension のバックグラウンドページとタイマー

+ +

WebExtension のバックグラウンドページでは、タイマーが正しく動作しません。これはバックグラウンドページが実際には常にロードされたままではないからです。ブラウザ-は使用されていない場合はアンロードし、必要なときに復元することができます。これは拡張機能にはほとんど透過的ですが、いくつかのもの (JS タイマーを含む) はアンロード/リストアサイクル全体では動作しないので、バックグラウンドページは代わりにアラームを使うことを推奨します。これについての詳細は Migrate to Event Driven Background Scripts にあります。

+ +

この記事の執筆時点では、 Chrome だけが上記の挙動を示していました - Firefox はまだアンロード/リストアの挙動をしていないので、タイマーは動作するでしょう。しかし、いくつかの理由から WebExtensions でタイマーを使わないようにするのはまだ良い考えです。

+ +
    +
  1. Chrome との互換性のため
  2. +
  3. 将来、動作が変更された場合に問題が発生する可能性があるため
  4. +
+ +

最大遅延時間

+ +

Internet Explorer、Chrome、Safari、Firefox を含むブラウザーは、内部で遅延時間を 32 ビット符号付き整数値で保存します。このため 2,147,483,647 ms (約 24.8 日) より大きな遅延時間を使用すると整数値がオーバーフローして、その結果直ちに実行されるタイムアウトになります。

+ +

仕様書

+ + + + + + + + + + + + + + + + + + + + + +
仕様書状態備考
{{SpecName('HTML WHATWG', 'webappapis.html#dom-settimeout', 'WindowOrWorkerGlobalScope.setTimeout()')}}{{Spec2("HTML WHATWG")}}最新の仕様で、メソッドを WindowOrWorkerGlobalScope ミックスインに移動。
{{SpecName("HTML WHATWG", "webappapis.html#dom-settimeout", "WindowTimers.setTimeout()")}}{{Spec2("HTML WHATWG")}}初回定義 (DOM Level 0)
+ +

ブラウザーの互換性

+ +

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

+ +

関連情報

+ + diff --git a/files/ja/web/api/windoworworkerglobalscope/atob/index.html b/files/ja/web/api/windoworworkerglobalscope/atob/index.html deleted file mode 100644 index 4408d9319b..0000000000 --- a/files/ja/web/api/windoworworkerglobalscope/atob/index.html +++ /dev/null @@ -1,92 +0,0 @@ ---- -title: WindowOrWorkerGlobalScope.atob() -slug: Web/API/WindowOrWorkerGlobalScope/atob -tags: - - API - - HTML DOM - - Method - - Reference - - WindowOrWorkerGlobalScope - - atob -translation_of: Web/API/WindowOrWorkerGlobalScope/atob -original_slug: Web/API/WindowBase64/atob ---- -

{{APIRef("HTML DOM")}}

- -

WindowOrWorkerGlobalScope.atob() 関数は、 {{glossary("Base64")}} エンコーディングでエンコードされたデータの文字列をデコードします。 {{domxref("WindowOrWorkerGlobalScope.btoa","btoa()")}} メソッドを使用して、通信に問題が発生する可能性のあるデータをエンコードして送信し、送信した後に atob() メソッドを使用して再度デコードすることができます。例えば、ASCII の 0 から 31 までのコードような制御文字をエンコードして送信し、デコードすることができます。

- -

Unicode や UTF-8 文字列の使用については、 {{domxref("WindowOrWorkerGlobalScope.btoa", "btoa()")}} の「Uncode 文字列」の節を参照してください。

- -

構文

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

引数

- -
-
encodedData
-
エンコードされたデータが入っているバイナリ文字列です。
-
- -

返値

- -

encodedData をデコードしたデータを含む ASCII 文字列です。

- -

例外

- -
-
{{domxref("DOMException")}} (name: InvalidCharacterError)
-
encodedData が妥当な base64 ではない場合に発行されます。
-
- -

- -
const encodedData = window.btoa('Hello, world'); // 文字列をエンコード
-const decodedData = window.atob(encodedData); // 文字列をデコード
- -

ポリフィル

- -

対応していないブラウザーでは、 https://github.com/MaxArt2501/base64-js/blob/master/base64.js のポリフィルを利用することができます。

- -

仕様書

- - - - - - - - - - - - - - - - - - - - - - - - - - -
仕様書状態備考
{{SpecName('HTML WHATWG', '#dom-atob', 'WindowOrWorkerGlobalScope.atob()')}}{{Spec2('HTML WHATWG')}}最新の仕様で、メソッドを WindowOrWorkerGlobalScope ミックスインに移動。
{{SpecName('HTML5.1', '#dom-windowbase64-atob', 'WindowBase64.atob()')}}{{Spec2('HTML5.1')}}{{SpecName("HTML WHATWG")}} のスナップショット、変更なし。
{{SpecName("HTML5 W3C", "#dom-windowbase64-atob", "WindowBase64.atob()")}}{{Spec2('HTML5 W3C')}}{{SpecName("HTML WHATWG")}} のスナップショット。 WindowBase64 の作成 (以前の対象だったプロパティ)。
- -

ブラウザーの互換性

- -
-

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

-
- -

関連情報

- - diff --git a/files/ja/web/api/windoworworkerglobalscope/btoa/index.html b/files/ja/web/api/windoworworkerglobalscope/btoa/index.html deleted file mode 100644 index da5c8c872d..0000000000 --- a/files/ja/web/api/windoworworkerglobalscope/btoa/index.html +++ /dev/null @@ -1,144 +0,0 @@ ---- -title: WindowOrWorkerGlobalScope.btoa() -slug: Web/API/WindowOrWorkerGlobalScope/btoa -tags: - - API - - HTML DOM - - Method - - Reference - - Web - - WindowOrWorkerGlobalScope - - btoa - - data - - strings -translation_of: Web/API/WindowOrWorkerGlobalScope/btoa ---- -

{{APIRef("HTML DOM")}}

- -

WindowOrWorkerGlobalScope.btoa() メソッドは、 {{glossary("Base64")}} でエンコードされた ASCII 文字列をバイナリ文字列 (例えば {{jsxref("String")}} オブジェクトのうち、文字列中のすべての文字がバイナリデータのバイトとして扱うことができるもの) から生成します。

- -

このメソッドを使用すると、通信に支障をきたす可能性のあるデータをエンコードして送信し、その後 {{domxref("WindowOrWorkerGlobalScope.atob", "atob()")}} メソッドを使用して再度デコードすることができます。例えば ASCII で 0 から 31 の値ような制御文字をエンコードすることもできます。

- -

構文

- -
var encodedData = scope.btoa(stringToEncode);
- -

引数

- -
-
stringToEncode
-
エンコードするバイナリ文字列です。
-
- -

返値

- -

stringToEncode の Base64 表現である ASCII 文字列です。

- -

例外

- -
-
InvalidCharacterError
-
文字列には、1 バイトに収まらない文字が含まれていた場合。詳細は後述の「Unicode文字列」を参照してください。
-
- -

- -
const encodedData = window.btoa('Hello, world'); // 文字列をエンコード
-const decodedData = window.atob(encodedData); // 文字列をデコード
-
- -

Unicode 文字列

- -

btoa() 関数は、JavaScript の文字列を引数にとります。JavaScript の文字列は UTF-16 文字エンコーディングで表現されます。このエンコーディングでは、文字列は 16 ビット (2 バイト) 単位の並びとして表現されます。すべての ASCII 文字はこれらの単位の 1 バイト目に収まりますが、他の多くの文字は収まりません。

- -

Base64 は、設計上、バイナリデータを入力として期待します。 JavaScript の文字列では、これは各文字が 1 バイトしか占有しない文字列を意味します。したがって、2 バイト以上の文字を含む文字列を btoa() に渡した場合、これはバイナリデータとはみなされないため、エラーが発生します。

- -
const ok = "a";
-console.log(ok.codePointAt(0).toString(16)); //   61: 長さ < 1 バイト
-
-const notOK = "✓"
-console.log(notOK.codePointAt(0).toString(16)); // 2713: 長さ > 1 バイト
-
-console.log(btoa(ok));    // YQ==
-console.log(btoa(notOK)); // error
- -

btoa() を用いて Unicode テキストを ASCII としてエンコードする必要がある場合、一つの選択肢として、各 16 ビット単位が 1 バイトしか占有しないように文字列を変換することができます。例えば、以下のようになります。

- -
// Unicode 文字列で、各 16 ビット単位を 1 バイトしか占有
-// しない文字列に変換します。
-function toBinary(string) {
-  const codeUnits = new Uint16Array(string.length);
-  for (let i = 0; i < codeUnits.length; i++) {
-    codeUnits[i] = string.charCodeAt(i);
-  }
-  return String.fromCharCode(...new Uint8Array(codeUnits.buffer));
-}
-
-// 1 バイトを超える文字を含んだ文字列
-const myString = "☸☹☺☻☼☾☿";
-
-const converted = toBinary(myString);
-const encoded = btoa(converted);
-console.log(encoded);                 // OCY5JjomOyY8Jj4mPyY=
-
- -

このようにした場合、当然ながらデコードされた文字列を逆変換する必要があります。

- -
function fromBinary(binary) {
-  const bytes = new Uint8Array(binary.length);
-  for (let i = 0; i < bytes.length; i++) {
-    bytes[i] = binary.charCodeAt(i);
-  }
-  return String.fromCharCode(...new Uint16Array(bytes.buffer));
-}
-
-const decoded = atob(encoded);
-const original = fromBinary(decoded);
-console.log(original);                // ☸☹☺☻☼☾☿
-
- -

ポリフィル

- -

対応していないブラウザーでは、 https://github.com/MaxArt2501/base64-js/blob/master/base64.js のポリフィルを利用することができます。

- -

仕様書

- - - - - - - - - - - - - - - - - - - - - - - - - - -
仕様書状態備考
{{SpecName('HTML WHATWG', '#dom-btoa', 'WindowOrWorkerGlobalScope.btoa()')}}{{Spec2('HTML WHATWG')}}最新の仕様で、メソッドを WindowOrWorkerGlobalScope ミックスインに移動。
{{SpecName('HTML5.1', '#dom-windowbase64-btoa', 'WindowBase64.btoa()')}}{{Spec2('HTML5.1')}}{{SpecName("HTML WHATWG")}} のスナップショット、変更なし。
{{SpecName("HTML5 W3C", "#dom-windowbase64-btoa", "WindowBase64.btoa()")}}{{Spec2('HTML5 W3C')}}{{SpecName("HTML WHATWG")}} のスナップショット。 WindowBase64 の作成 (properties where on the target before it).
- -

ブラウザーの互換性

- -
-

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

-
- -

関連情報

- - diff --git a/files/ja/web/api/windoworworkerglobalscope/caches/index.html b/files/ja/web/api/windoworworkerglobalscope/caches/index.html deleted file mode 100644 index 89583bbda5..0000000000 --- a/files/ja/web/api/windoworworkerglobalscope/caches/index.html +++ /dev/null @@ -1,83 +0,0 @@ ---- -title: WorkerGlobalScope.caches -slug: Web/API/WindowOrWorkerGlobalScope/caches -tags: - - API - - Experimental - - Property - - Read-only - - Reference - - Service Workers - - Web Workers - - Window - - WindowOrWorkerGlobalScope -translation_of: Web/API/WindowOrWorkerGlobalScope/caches -original_slug: Web/API/WorkerGlobalScope/caches ---- -
{{APIRef()}}{{SeeCompatTable}}
- -

{{domxref("WindowOrWorkerGlobalScope")}} インターフェイスの caches 読み取り専用プロパティは、現在のワーカーコンテキストに関連する {{domxref("CacheStorage")}} オブジェクトを返します。このオブジェクトにより、オフライン利用のために資産 (assets、アセット) を保存したり、リクエストに対するカスタムレスポンスを生成したりするなどの機能を使用できます。

- -

構文

- -
var myCacheStorage = self.caches; // または単に caches
-
- -

- -

{{domxref("CacheStorage")}}。

- -

- -

次の例では、アセットをオフラインで利用できるようにするために、ServiceWorker コンテキストでキャッシュを使う方法を示しています。

- -
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'
-      );
-    })
-  );
-});
- -

仕様

- - - - - - - - - - - - - - -
仕様ステータスコメント
{{SpecName('Service Workers')}}{{Spec2('Service Workers')}}初期定義。
- -

ブラウザー実装状況

- - - -

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

- -

関連項目

- - diff --git a/files/ja/web/api/windoworworkerglobalscope/clearinterval/index.html b/files/ja/web/api/windoworworkerglobalscope/clearinterval/index.html deleted file mode 100644 index f3e9b52e6d..0000000000 --- a/files/ja/web/api/windoworworkerglobalscope/clearinterval/index.html +++ /dev/null @@ -1,67 +0,0 @@ ---- -title: window.clearInterval -slug: Web/API/WindowOrWorkerGlobalScope/clearInterval -tags: - - DOM - - DOM_0 - - Gecko - - JavaScript timers - - Window -translation_of: Web/API/WindowOrWorkerGlobalScope/clearInterval -original_slug: Web/API/WindowTimers/clearInterval ---- -
{{ApiRef}}
- -

概要

- -

{{domxref("window.setInterval", "setInterval")}} を使用して設定された繰り返し動作をキャンセルします。

- -

構文

- -
window.clearInterval(intervalID)
-
- - - -

- -

{{domxref("window.setInterval", "setInterval()", "example")}} の例を参照して下さい。

- -

仕様

- - - - - - - - - - - - - - - - - - - -
仕様書策定状況コメント
{{SpecName('HTML WHATWG', 'webappapis.html#dom-setInterval', 'WindowOrWorkerGlobalScope.clearInterval()')}}{{Spec2("HTML WHATWG")}}最新の仕様で、メソッドを WindowOrWorkerGlobalScope ミックスインに移動。
{{SpecName("HTML WHATWG", "webappapis.html#dom-setInterval", "WindowTimers.setInterval()")}}{{Spec2("HTML WHATWG")}} 
- -

ブラウザー実装状況

- -

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

- -

関連情報

- - diff --git a/files/ja/web/api/windoworworkerglobalscope/cleartimeout/index.html b/files/ja/web/api/windoworworkerglobalscope/cleartimeout/index.html deleted file mode 100644 index 2ce0bb071e..0000000000 --- a/files/ja/web/api/windoworworkerglobalscope/cleartimeout/index.html +++ /dev/null @@ -1,100 +0,0 @@ ---- -title: WindowOrWorkerGlobalScope.clearTimeout() -slug: Web/API/WindowOrWorkerGlobalScope/clearTimeout -tags: - - API - - HTML DOM - - Method - - Reference - - WindowOrWorkerGlobalScope - - clearTimeout - - メソッド - - リファレンス -translation_of: Web/API/WindowOrWorkerGlobalScope/clearTimeout ---- -
{{APIRef("HTML DOM")}}
- -

clearTimeout() は {{domxref("WindowOrWorkerGlobalScope")}} ミックスインのメソッドで、以前の {{domxref("WindowOrWorkerGlobalScope.setTimeout", "setTimeout()")}} の呼び出しによって以前に確立されたタイムアウトを解除します。

- -

構文

- -
scope.clearTimeout(timeoutID)
-
- -

引数

- -
-
timeoutID
-
解除したいタイマの ID です。 ID は setTimeout() の返値によって取得できます。
-
- -

注目すべきは、 {{domxref("WindowOrWorkerGlobalScope.setTimeout", "setTimeout()")}} および {{domxref("WindowOrWorkerGlobalScope.setInterval", "setInterval()")}} で使用される ID のプールは共有されますので、技術的には clearTimeout() および {{domxref("WindowOrWorkerGlobalScope.clearInterval", "clearInterval()")}} は互いに交換できます。しかし、明確化のため、そのようなことは避けてください。

- -

- -

ウェブページのコンテキストで以下のスクリプトを実行し、ページを一度クリックしてください。1秒後にメッセージがポップアップします。1秒間に複数回ページをクリックしても、アラートは一度しか表示されません。

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

メモ

- -

clearTimeout() へ妥当ではない ID を渡しても、何の効果もありません。例外は発生しません。

- -

仕様書

- - - - - - - - - - - - - - - - - - - - - -
仕様書状態備考
{{SpecName('HTML WHATWG', 'webappapis.html#dom-cleartimeout', 'WindowOrWorkerGlobalScope.clearTimeout()')}}{{Spec2("HTML WHATWG")}}最新の仕様で、メソッドを WindowOrWorkerGlobalScope ミックスインに移動。
{{SpecName('HTML WHATWG', 'webappapis.html#dom-cleartimeout', 'clearTimeout()')}}{{Spec2('HTML WHATWG')}}
- -

ブラウザーの互換性

- -

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

- -

関連情報

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

createImageBitmap() メソッドは、指定されたソースからビットマップを作成します。このメソッドは、windows と worker の両方のグローバルスコープに存在します。このメソッドは、さまざまな異なる画像ソースを受け付け、{{domxref("Promise")}} を返し、{{domxref("ImageBitmap")}} に解決します。

- -

シンタックス

- -
const imageBitmapPromise = createImageBitmap(image[, options]);
-const imageBitmapPromise = createImageBitmap(image, sx, sy, sw, sh[, options]);
- -

パラメータ

- -
-
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
-
ImageBitmap が抽出される矩形の参照点の x 座標。
-
sy
-
ImageBitmap が抽出される矩形の参照点の y 座標。
-
sw
-
ImageBitmap が抽出される矩形の幅。この値は負の値にすることができます。
-
sh
-
ImageBitmap が抽出される矩形の高さ。この値は負の値にすることができます。
-
options {{optional_inline}}
-
画像の抽出のためのオプションを設定するオブジェクト。利用可能なオプションは以下の通りです。 -
    -
  • imageOrientation: 画像をそのまま表示するか、垂直方向に反転させて表示するかを指定します。none (デフォルト) または flipY のいずれかを指定します
  • -
  • premultiplyAlpha: ビットマップのカラーチャンネルをアルファチャンネルで前置増幅するかどうかを指定します。nonepremultiplydefault (デフォルト) のいずれかです
  • -
  • colorSpaceConversion: 画像を色空間変換でデコードするかどうかを指定します。none または default (デフォルト) のいずれかを指定します。値 default は、実装固有の動作を使用することを示します
  • -
  • resizeWidth: 出力幅を示す long 整数
  • -
  • resizeHeight: 出力の高さを示す long 整数
  • -
  • resizeQuality: 出力寸法に合わせて入力のサイズを変更するために使用するアルゴリズムを指定します。pixelatedlow (デフォルト)、mediumhighのいずれかです
  • -
-
-
- -

戻り値

- -

与えられた矩形のビットマップデータを含む{{domxref("ImageBitmap")}} オブジェクトに解決する{{domxref("Promise")}} を返します。

- -

- -

スプライトシートからのスプライト作成

- -

この例では、スプライトシートをロードし、個々のスプライトを抽出し、各スプライトをキャンバスにレンダリングします。スプライトシートとは、複数の小さな画像を含む画像で、それぞれを個別にレンダリングできるようにしたいものです。

- -
var canvas = document.getElementById('myCanvas'),
-ctx = canvas.getContext('2d'),
-image = new Image();
-
-// スプライトシートがロードされるのを待ちます
-image.onload = function() {
-  Promise.all([
-    // スプライトシートから2つのスプライトを切り取ります
-    createImageBitmap(image, 0, 0, 32, 32),
-    createImageBitmap(image, 32, 0, 32, 32)
-  ]).then(function(sprites) {
-    // 各スプライトをキャンバスに描きます
-    ctx.drawImage(sprites[0], 0, 0);
-    ctx.drawImage(sprites[1], 32, 32);
-  });
-}
-
-// 画像ファイルからスプライトシートを読み込みます
-image.src = 'sprites.png';
-
- -

仕様

- - - - - - - - - - - - - - -
仕様書ステータスコメント
{{SpecName('HTML WHATWG', "webappapis.html#dom-createimagebitmap", "createImageBitmap")}}{{Spec2('HTML WHATWG')}}
- -

ブラウザの互換性

- -

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

- -

あわせて参照

- - diff --git a/files/ja/web/api/windoworworkerglobalscope/fetch/index.html b/files/ja/web/api/windoworworkerglobalscope/fetch/index.html deleted file mode 100644 index 05704bb11f..0000000000 --- a/files/ja/web/api/windoworworkerglobalscope/fetch/index.html +++ /dev/null @@ -1,191 +0,0 @@ ---- -title: WindowOrWorkerGlobalScope.fetch() -slug: Web/API/WindowOrWorkerGlobalScope/fetch -tags: - - API - - Experimental - - Fetch - - Fetch API - - GlobalFetch - - Method - - Reference - - WindowOrWorkerGlobalScope - - request - - メソッド -translation_of: Web/API/WindowOrWorkerGlobalScope/fetch ---- -

{{APIRef("Fetch API")}}

- -

fetch() は {{domxref("WindowOrWorkerGlobalScope")}} ミックスインのメソッドで、ネットワークからリソースを取得するプロセスを開始し、レスポンスが利用できるようになったら満足するプロミスを返します。このプロミスはリクエストに対するレスポンスを表す {{domxref("Response")}} で解決します。プロミスは HTTP エラーでは拒否されず、ネットワークエラーでのみ拒否されます。 HTTP エラーをチェックするには、 then ハンドラーを使用する必要があります。

- -

WindowOrWorkerGlobalScope は {{domxref("Window")}} と {{domxref("WorkerGlobalScope")}} の両方で実装されています。これはつまり fetch() メソッドはあなたがリソースを取得したいと思うような大部分コンテキストで使用可能ということです。

- -

{{domxref("WindowOrWorkerGlobalScope.fetch","fetch()")}} のプロミスはネットワークエラーが発生した場合 (すなわち普通はパーミッション問題などがあったとき) のみ拒否されます。 {{domxref("WindowOrWorkerGlobalScope.fetch","fetch()")}} のプロミスは HTTP エラー (404 など) では拒否されません。代わりに、 then() ハンドラーで {{domxref("Response.ok")}} や {{domxref("Response.status")}} プロパティをチェックする必要があります。

- -

fetch() メソッドは取得するリソースのディレクティブではなく Content Security Policyconnect-src ディレクティブによって制御されます。

- -
-

: fetch() メソッドの引数は {{domxref("Request.Request","Request()")}} コンストラクターと全く同じです。

-
- -

構文

- -
const fetchResponsePromise = fetch(resource [, init])
-
- -

引数

- -
-
resource
-
取得したいリソースを定義します。以下の 2 つが使用出来ます。 -
    -
  • 取得したいリソースの直接の URL を含む {{domxref("USVString")}}。ブラウザーによってはスキームとして blob:data: を受け入れます。
  • -
  • {{domxref("Request")}} オブジェクト。
  • -
-
-
init {{optional_inline}}
-
-

リクエストに適用したいカスタム設定を含むオブジェクト。可能なオプションは以下の通りです。

- -
-
method
-
リクエストするメソッド、GETPOST など。なお、 {{httpheader("Origin")}} ヘッダーは {{HTTPMethod("HEAD")}} または {{HTTPMethod("GET")}} メソッドの読み取りリクエストでは設定されません。
- (この動作は Firefox 65 で修正されました — {{bug(1508661)}} を参照)
-
headers
-
リクエストに追加したいヘッダーで、{{domxref("Headers")}} オブジェクトか {{domxref("ByteString")}} 値を持つオブジェクトリテラルで指定してください。なお、一部の名前は禁止されています
-
body
-
リクエストに追加したい本文です。これには {{domxref("Blob")}}, {{domxref("BufferSource")}}, {{domxref("FormData")}}, {{domxref("URLSearchParams")}}, {{domxref("USVString")}}, {{domxref("ReadableStream")}} オブジェクトなどが使用できます。メソッドが GETHEAD の場合使用できないので注意してください。
-
mode
-
リクエストで使いたいモードです。例: cors, no-cors, same-origin
-
credentials
-
リクエストに使用したいリクエスト認証情報、 omit, same-origin, include です。現在のドメインの Cookie を自動で送るためにはこのオプションを指定する必要があります。 Chrome 50 から、このプロパティは{{domxref("FederatedCredential")}} インスタンスや {{domxref("PasswordCredential")}} インスタンスを受け付けるようになりました。
-
cache
-
使用したいリクエストのキャッシュモードです。
-
redirect
-
使用するリダイレクトモードです。 follow (自動でリダイレクトに従う)、 error (リダイレクトが起こった場合エラーを伴って中止する)、 manual (手動でリダイレクトを処理する)。Chrome の既定値は follow です (バージョン 47 より前の既定値は manual でした)。
-
referrer
-
{{domxref("USVString")}} でリクエストのリファラーを指定します。これは同じオリジンの URL、 about:client、空文字列のいずれかを取ることができます。
-
referrerPolicy
-
リクエストで使用するリファラーポリシーを指定します。使用可能な値は、 no-referrer, no-referrer-when-downgrade, same-origin, origin, strict-origin, origin-when-cross-origin, strict-origin-when-cross-origin, or unsafe-url のいずれかです。
-
integrity
-
リソースに subresource integrity 値を含ませることが出来ます (例:sha256-BpfBw7ivV8q2jLiT13fxDYAe2tJllusRSZ273h2nFSE=)。
-
keepalive
-
keepalive オプションはページより長生きするリクエストを許可するのに使われます。keepalive フラグつきの Fetch は{{domxref("Navigator.sendBeacon()")}} API の置き換えです。
-
signal
-
{{domxref("AbortSignal")}} オブジェクトのインスタンスです。つまり {{domxref("AbortController")}} 経由で fetch リクエストと通信したり望む場合には中止したりできます。
-
-
-
- -

返値

- -

{{domxref("Promise")}} で、 {{domxref("Response")}} オブジェクトに解決します。

- -

例外

- -
-
AbortError
-
{{domxref("AbortController")}} メソッドまたは {{domxref("AbortController.abort", "abort()")}} メソッドの呼び出しによりリクエストが中止された。
-
TypeError
-
指定された URL がユーザー認証情報を含んでいる。この情報は {{HTTPHeader("Authorization")}} ヘッダーを用いて提供するべきです。
-
- -

- -

Fetch Request example リポジトリ (デモ: Fetch Request live) では {{domxref("Request")}} オブジェクトを関連するコンストラクターを使って作成しています。その後 fetch() を呼んで取得しています。画像を fetch している時から適切な MIME タイプを与えるために response の {{domxref("Body.blob")}} を実行し、適切に処理されます。そして ObjectURL を作成し {{htmlelement("img")}} 要素に追加して表示させています。

- -
const myImage = document.querySelector('img');
-
-let myRequest = new Request('flowers.jpg');
-
-fetch(myRequest)
-.then(function(response) {
-  if (!response.ok) {
-    throw new Error(`HTTP error! status: ${response.status}`);
-  }
-  return response.blob();
-})
-.then(function(response) {
-  let objectURL = URL.createObjectURL(response);
-  myImage.src = objectURL;
-});
- -

Fetch with init then Request example リポジトリ (デモ: Fetch Request init live) では上記の内容に加えて、fetch() を呼び出すとき、初期化オブジェクト init を渡しています。

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

同様に init オブジェクトを Request コンストラクターに渡しても、同じ効果が得られます。

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

initinit としてオブジェクトリテラルを使用することもできます。

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

仕様書

- - - - - - - - - - - - - - - - - - - - - - - - - - -
仕様書状態備考
{{SpecName('Fetch','#fetch-method','fetch()')}}{{Spec2('Fetch')}}最新の仕様では WindowOrWorkerGlobalScope の中で部分的に定義。
{{SpecName('Fetch','#dom-global-fetch','fetch()')}}{{Spec2('Fetch')}}初回定義
{{SpecName('Credential Management')}}{{Spec2('Credential Management')}}{{domxref("FederatedCredential")}} または {{domxref("PasswordCredential")}} のインスタンスを init.credentials の値として追加。
- -

ブラウザーの互換性

- -

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

- -

関連情報

- - diff --git a/files/ja/web/api/windoworworkerglobalscope/indexeddb/index.html b/files/ja/web/api/windoworworkerglobalscope/indexeddb/index.html deleted file mode 100644 index ae7659a244..0000000000 --- a/files/ja/web/api/windoworworkerglobalscope/indexeddb/index.html +++ /dev/null @@ -1,71 +0,0 @@ ---- -title: WindowOrWorkerGlobalScope.indexedDB -slug: Web/API/WindowOrWorkerGlobalScope/indexedDB -tags: - - API - - Database - - IndexedDB - - Property - - Reference - - Storage -translation_of: Web/API/WindowOrWorkerGlobalScope/indexedDB ---- -

{{ APIRef() }}

- -

{{domxref("WindowOrWorkerGlobalScope")}} ミックスインの indexedDB 読み取り専用プロパティは、アプリケーションが indexed データベースのキャパビリティに非同期でアクセスするための機構を提供します。

- -

構文

- -
var IDBFactory = self.indexedDB;
- -

- -

{{domxref("IDBFactory")}} オブジェクト。

- -

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

仕様

- - - - - - - - - - - - - - - - - - - -
仕様書策定状況備考
{{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')}}初期定義。
- -

ブラウザーの実装状況

- -

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

- -

関連情報

- - diff --git a/files/ja/web/api/windoworworkerglobalscope/issecurecontext/index.html b/files/ja/web/api/windoworworkerglobalscope/issecurecontext/index.html deleted file mode 100644 index 221ce43915..0000000000 --- a/files/ja/web/api/windoworworkerglobalscope/issecurecontext/index.html +++ /dev/null @@ -1,56 +0,0 @@ ---- -title: WindowOrWorkerGlobalScope.isSecureContext -slug: Web/API/WindowOrWorkerGlobalScope/isSecureContext -tags: - - API - - DOM - - Window - - WindowOrWorkerGlobalContext - - Workers - - isSecureContext - - ウェブ - - プロパティ - - リファレンス -translation_of: Web/API/WindowOrWorkerGlobalScope/isSecureContext ---- -

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

- -

{{domxref("WindowOrWorkerGlobalScope")}} インターフェイスの読み取り専用 isSecureContext プロパティは、現在のコンテキストが安全(true)かそうではない(false)を示すブール値を返します。

- -

構文

- -
var isItSecure = self.isSecureContext; // or just isSecureContext
-
- -

- -

{{domxref("Boolean")}}.

- -

仕様

- - - - - - - - - - - - - - -
仕様ステータスコメント
{{SpecName('Secure Contexts', '#dom-windoworworkerglobalscope-issecurecontext', 'WindowOrWorkerGlobalScope.isSecureContext')}}{{Spec2('Secure Contexts')}}初期定義。
- -

ブラウザ互換性

- - - -

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

- -

参照

- - diff --git a/files/ja/web/api/windoworworkerglobalscope/origin/index.html b/files/ja/web/api/windoworworkerglobalscope/origin/index.html deleted file mode 100644 index 834af4741a..0000000000 --- a/files/ja/web/api/windoworworkerglobalscope/origin/index.html +++ /dev/null @@ -1,58 +0,0 @@ ---- -title: WindowOrWorkerGlobalScope.origin -slug: Web/API/WindowOrWorkerGlobalScope/origin -tags: - - API - - DOM - - Window - - WindowOrWorkerGlobalScope - - Worker - - ウェブ - - プロパティ -translation_of: Web/API/WindowOrWorkerGlobalScope/origin ---- -

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

- -

{{domxref("WindowOrWorkerGlobalScope")}} インターフェイスの読み取り専用プロパティ origin は、グローバルスコープの文字列としてシリアライズされた origin を返します。

- -

構文

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

- -

{{domxref("USVString")}}.

- -

- -

worker script 内から実行される以下のスニペットは、メッセージを受け取る度にワーカーのグローバルスコープの origin をコンソールに記録します。

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

もし origin が scheme/host/port tuple出ない場合 (あなたがローカルで実行しようとしている、言い換えると file:// というURLの場合)、 origin は "null" という文字列を返すでしょう。

- -

仕様

- - - - - - - - - - - - - - -
仕様ステータスコメント
{{SpecName('HTML WHATWG', 'webappapis.html#dom-origin', 'WindowOrWorkerGlobalScope.origin')}}{{Spec2('HTML WHATWG')}}初期定義。
- -

ブラウザ互換性

- - - -

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

diff --git a/files/ja/web/api/windoworworkerglobalscope/setinterval/index.html b/files/ja/web/api/windoworworkerglobalscope/setinterval/index.html deleted file mode 100644 index 543639410e..0000000000 --- a/files/ja/web/api/windoworworkerglobalscope/setinterval/index.html +++ /dev/null @@ -1,635 +0,0 @@ ---- -title: WindowOrWorkerGlobalScope.setInterval() -slug: Web/API/WindowOrWorkerGlobalScope/setInterval -tags: - - API - - DOM - - Gecko - - Intervals - - JavaScript timers - - MakeBrowserAgnostic - - Method - - NeedsMarkupWork - - Timers - - WindowOrWorkerGlobalScope - - setInterval -translation_of: Web/API/WindowOrWorkerGlobalScope/setInterval ---- -
{{APIRef("HTML DOM")}}
- -

{{domxref("WindowOrWorkerGlobalScope")}} ミックスインの setInterval() メソッドは、一定の遅延間隔を置いて関数やコードスニペットを繰り返し呼び出します。これは、インターバルを一意に識別する interval ID を返します。よって {{domxref("WindowOrWorkerGlobalScope.clearInterval", "clearInterval()")}} を呼び出して、後でインターバルを削除できます。このメソッドは {{domxref("Window")}} および {{domxref("Worker")}} インターフェイスで提供します。

- -

構文

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

引数

- -
-
func
-
ミリ秒単位の delay が経過するたびに実行する {{jsxref("function", "関数")}} です。関数には引数が渡されず、また戻り値を想定していません。
-
code
-
関数の代わりに文字列を含める構文も許容されており、ミリ秒単位の delay が経過するたびに文字列をコンパイルして実行します。{{jsxref("eval", "eval()")}} の使用にリスクがあるのと同じ理由で、この構文は 推奨しません
-
delay
-
指定した関数またはコードを実行する前にタイマーが待つべき時間をミリ秒 (1/1000 秒) 単位で指定します。引数が 10 より小さい場合は、10 を使用します。実際の遅延が長くなることがあります。例えば {{SectionOnPage("/ja/docs/Web/API/WindowOrWorkerGlobalScope/setTimeout", "遅延が指定値より長い理由")}} をご覧ください。
-
param1, ..., paramN {{optional_inline}}
-
タイマーが満了したときに、func で指定した関数に渡す追加の引数です。
-
- -
-

注記: Internet Explorer 9 およびそれ以前のバージョンでは、最初の構文で setInterval() に渡す追加の引数は動作しないことに注意してください。同様の機能を実現させるには、ポリフィルを使用してください。(コールバックの引数 を参照)。

-
- -

戻り値

- -

戻り値 intervalID は、setInterval() を呼び出して作成したタイマーを識別する、0 ではない正の整数値です。この値は、インターバルをキャンセルするために {{domxref("WindowOrWorkerGlobalScope.clearInterval()")}} へ渡すことができます。

- -

setInterval() と {{domxref("WindowOrWorkerGlobalScope.setTimeout", "setTimeout()")}} は同じ ID プールを共有しており、さらに clearInterval() と {{domxref("WindowOrWorkerGlobalScope.clearTimeout", "clearTimeout()")}} は技術的に入れ替えて使用できることを意識すると役に立つでしょう。ただし明快さのために、コードを整備するときは混乱を避けるため、常に一致させるようにするべきです。

- -
注記: 引数 delay は、符号付き 32 ビット整数に変換されます。IDL における符号付き整数の定義によって、delay は事実上 2147483647ms に制限されます。
- -

- -

例 1: 基本的な構文

- -

以下の例は、setInterval() の基本的な構文を示します。

- -
var intervalID = window.setInterval(myCallback, 500);
-
-function myCallback() {
-  // Your code here
-}
-
- -

例 2: 2 つの色を切り替える

- -

以下の例は停止ボタンを押すまで、1 秒おきに flashtext() 関数を呼び出します。

- -
<!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>
-<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>
- -

View this demo in action. See also: 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[, param1, param2, ...]);
-|*|  var timeoutID = window.setTimeout(code, delay);
-|*|  var intervalID = window.setInterval(func, delay[, param1, param2, ...]);
-|*|  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);
- -

さらに、関数の bind を使用する方法もあります。例えば:

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

{{h3_gecko_minversion("非アクティブなタブ", "5.0")}}

- -

Gecko 5.0 {{geckoRelease("5.0")}} より非アクティブなタブでは、1 秒あたり 1 回を超えて実行しないようにインターバルを制限します。

- -

"this" 問題

- -

setInterval() (もっと言うと他のどんな関数でも) にメソッドを渡すと、間違った this の値で呼び出されることがあります。この問題は JavaScript リファレンス で詳しく説明されています。

- -

説明

- -

setInterval() によって実行されるコードは、setInterval が呼び出された関数とは別の実行コンテキスト内で実行されます。その結果、呼び出された関数の this キーワードは window (または global) オブジェクトに設定されます。これは setTimeout を呼び出した関数の this の値とは異なります。以下の例をご覧ください (ここでは setInterval() ではなく setTimeout() を使用していますが、どちらのタイマーでも問題は同じです):

- -
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
-
- -

この例でわかるとおり、旧来の JavaScript でコールバック関数に this オブジェクトを渡す方法はありません。

- -

考えられる解決策

- -

"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);
-};
- -
これら 2 つの置き換えにより、IE のタイマーで HTML5 標準の、コールバック関数に任意の引数を渡すことも可能になります。よって、標準仕様に準拠しない ポリフィルとしても使用できます。標準仕様に準拠するポリフィルについては、コールバックの引数 をご覧ください。
- -

新機能のテスト:

- -
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
-
- -

この他に this 問題のより複雑な解決策として、後述するフレームワーク もあります。

- -
JavaScript 1.8.5 で、関数のすべての呼び出しで this として使用する値を設定できる、Function.prototype.bind() メソッドを導入しました。これにより、関数を呼び出したコンテキストに応じて this がどのようになるかが明確にならない問題を簡単に回避できます。また、ES2015 では アロー関数 をサポートして、字句 this と組み合わせると myArray の内部では setInterval( () => this.myMethod) と記述できます。
- -

MiniDaemon: タイマー管理フレームワーク

- -

多くのタイマーが必要なページでは、実行中のタイマーのイベントをすべて追跡し続けることが困難な場合があります。この問題の解決策のひとつが、オブジェクト内のタイマーの状態に関する情報を保存することです。以下のコードは、そのような抽象化の最小限の例です。コンストラクターは、クロージャの使用を明示的に避けるアーキテクチャになっています。また、this オブジェクトをコールバック関数に渡す代替手段も提供します (詳しくは "this" 問題 をご覧ください)。以下のコードは GitHub でも入手できます

- -
より複雑ですがモジュール化したもの (Daemon) については、JavaScript Daemons Management をご覧ください。このより複雑なバージョンは、Daemon コンストラクター用の大規模でスケーラブルなメソッドのコレクションに過ぎません。しかし Daemon コンストラクター自体は、daemon のインスタンス化の間に宣言可能な init および onstart 関数のサポートを追加した MiniDaemon のクローンに過ぎません。よって MiniDaemon フレームワークは、シンプルなアニメーションのために推奨する方法であり続けます。これは、メソッドのコレクションがない Daemon が本質的に MiniDaemon のクローンであるためです。
- -

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 は、引数をコールバック関数に渡します。この機能をネイティブにサポートしないブラウザーで動作させたい場合は、ここで提案したメソッドのいずれかを使用してください。
- -

構文

- -

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

- -

説明

- -

アニメーションで必要なすべての情報 (this オブジェクト、コールバック関数、長さ、フレームレート) を持つ JavaScript Object を返します。

- -

引数

- -
-
thisObject
-
コールバック関数が呼び出された this オブジェクト。object または null を使用できます。
-
callback
-
繰り返し実行する関数。これは 3 個の引数を伴って呼び出されますindex (反復処理の、毎回の処理のインデックス)、length (daemon に割り当てられた総実行回数。有限の数値または Infinity を指定できます)、backwards (index を加算するか減算するかを示す論理値)。これは callback.call(thisObject, index, length, backwards) のようなものです。コールバック関数が false 値を返す場合は、daemon が一時停止しています
-
rate (省略可能)
-
毎回の実行の時間間隔 (ミリ秒単位の数値)。デフォルト値は 100 です。
-
length (省略可能)
-
総実行回数。正の整数または Infinity を使用できます。デフォルト値は Infinity です。
-
- -

MiniDaemon インスタンスのプロパティ

- -
-
myDaemon.owner
-
daemon が実行される this オブジェクト (読み書き可能)。object または null を使用できます。
-
myDaemon.task
-
繰り返し実行する関数 (読み書き可能)。これは 3 個の引数を伴って呼び出されます。index (反復処理の、毎回の処理のインデックス)、length (daemon に割り当てられた総実行回数。有限の数値または Infinity を指定できます)、backwards (index 減算するか否かを示す論理値)。myDaemon.task の関数が false 値を返す場合は、daemon が一時停止しています。
-
myDaemon.rate
-
毎回の実行の時間間隔 (ミリ秒単位の数値、読み書き可能)。
-
myDaemon.length
-
総実行回数。正の整数または Infinity を使用できます (読み書き可能)。
-
- -

MiniDaemon インスタンスのメソッド

- -
-
myDaemon.isAtEnd()
-
daemon が開始/終了状態であるか否かを示す論理値を返します。
-
myDaemon.synchronize()
-
開始した daemon のタイマーと、daemon の実行時間を同期します。
-
myDaemon.pause()
-
daemon を一時停止します。
-
myDaemon.start([reverse])
-
daemon を前方 (毎回実行するたびに index が増加) または後方 (index が減少) に開始します。
-
- -

MiniDaemon グローバルオブジェクトのメソッド

- -
-
MiniDaemon.forceCall(minidaemon)
-
終端に達しているか否かの事実にかかわらず、minidaemon.task の関数へのひとつのコールバックを強制します。どの場合も、内部の INDEX プロパティは (実際の実行方向に応じて) 増加または減少します。
-
- -

使用例

- -

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>
- -

実際の動作例を見る

- -

注記

- -

setInterval() 関数は一般に、アニメーションのように何度も実行される関数に遅延をセットするのに使われます。

- -

{{domxref("WindowOrWorkerGlobalScope.clearInterval()")}} を使ってインターバルをキャンセルすることができます。

- -

指定時間後に 一度 だけ関数を呼び出したい場合には、{{domxref("WindowOrWorkerGlobalScope.setTimeout()")}} を使います。

- -

実行時間をインターバルより確実に短くする

- -

ロジックの実行時間がインターバル時間より長くなる可能性がある場合は、{{domxref("WindowOrWorkerGlobalScope.setTimeout")}} を使用して名前付き関数を再帰的に呼び出すことを推奨します。例えば 5 秒おきにリモートサーバーへ接続するために setInterval を使用するとき、ネットワークの遅延やサーバーの不応答などさまざまな問題で、割り当てられた時間内にリクエストが完了しない可能性があります。そのため、必ずしも順番どおりには返らない XHR リクエストがキュー内にあることに気づくかもしれません。

- -

この場合は、再帰的な setTimeout() のパターンを推奨します:

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

このコードスニペットでは、名前付き関数 loop() を宣言して直ちに実行します。loop() はロジックが完全に実行された後に、内部の setTimeout() によって再帰呼び出しされます。このパターンは一定の間隔で呼び出すことが保証されませんが、再帰呼び出しの前に前の実行が完了することが保証されます。

- -

インターバルを抑制する

- -

Firefox で setInterval() は、{{domxref("WindowOrWorkerGlobalScope.setTimeout","setTimeout()")}} と同様に、インターバルが制限されます。遅延が指定値より長い理由 をご覧ください。

- -

仕様

- - - - - - - - - - - - - - - - - - - -
仕様書策定状況コメント
{{SpecName('HTML WHATWG', 'webappapis.html#dom-setinterval', 'WindowOrWorkerGlobalScope.setInterval()')}}{{Spec2("HTML WHATWG")}}最新の仕様で、メソッドを WindowOrWorkerGlobalScope ミックスインに移動。
{{SpecName("HTML WHATWG", "webappapis.html#dom-setinterval", "WindowTimers.setInterval()")}}{{Spec2("HTML WHATWG")}}最初期の定義 (DOM Level 0)
- -

ブラウザー実装状況

- -
- - -

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

-
- -

関連情報

- - diff --git a/files/ja/web/api/windoworworkerglobalscope/settimeout/index.html b/files/ja/web/api/windoworworkerglobalscope/settimeout/index.html deleted file mode 100644 index 34c10664ce..0000000000 --- a/files/ja/web/api/windoworworkerglobalscope/settimeout/index.html +++ /dev/null @@ -1,419 +0,0 @@ ---- -title: WindowOrWorkerGlobalScope.setTimeout() -slug: Web/API/WindowOrWorkerGlobalScope/setTimeout -tags: - - API - - HTML DOM - - Intervals - - JavaScript timers - - MakeBrowserAgnostic - - Method - - NeedsCompatTable - - NeedsMarkupWork - - NeedsUpdate - - Reference - - Timers - - WindowOrWorkerGlobalScope - - setTimeout -translation_of: Web/API/WindowOrWorkerGlobalScope/setTimeout ---- -
{{APIRef("HTML DOM")}}
- -

setTimeout() は {{domxref("WindowOrWorkerGlobalScope")}} ミックスインのメソッド (および Window.setTimeout() の後継) で、時間切れになると関数または指定されたコードの断片を実行するタイマーを設定します。

- -

構文

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

引数

- -
-
function
-
タイマーが満了した後に実行したい {{jsxref("function", "関数")}}。
-
code
-
関数の代わりに文字列を含める代替構文も許容されており、タイマーが満了したときに文字列をコンパイルして実行します。 {{jsxref("Global_Objects/eval", "eval()")}} の使用にリスクがあるのと同じ理由で、この構文は推奨しません
-
delay {{optional_inline}}
-
指定した関数やコードを実行する前に待つタイマーの時間をミリ秒 (1/1000 秒) 単位で指定します。この引数を省略すると値 0 を使用しますので "直ちに" 実行する、より正確に言えばできるだけ早く実行することを意味します。どちらの場合も、実際の遅延が想定より長くなることがあります。後述する {{anch("Reasons for delays longer than specified", "遅延が指定値より長い理由")}} をご覧ください。
-
arg1, ..., argN {{optional_inline}}
-
タイマーが満了したときに、 function で指定された関数に渡す追加の引数です。
-
- -
-

: Internet Explorer 9 およびそれ以前のバージョンでは、最初の構文で関数に渡す追加の引数は動作しないことに注意してください。同様の機能を実現させるには、ポリフィルを使用してください。({{anch("Polyfill", "ポリフィル")}} を参照)。

-
- -

返値

- -

返される timeoutID は正の整数値で、 setTimeout() を呼び出して作成したタイマーを識別します。この値を {{domxref("WindowOrWorkerGlobalScope.clearTimeout","clearTimeout()")}} へ渡すことで、タイムアウトを取り消すことができます。

- -

setTimeout() と {{domxref("WindowOrWorkerGlobalScope.setInterval", "setInterval()")}} は同じ ID プールを共有しており、さらに clearTimeout() と {{domxref("WindowOrWorkerGlobalScope.clearInterval", "clearInterval()")}} は技術的に入れ替えて使用できることを意識すると役に立つかもしれません。ただし明確さのために、コードを整備するときは混乱を避けるため、常に一致させるようにするべきです。

- -

同じオブジェクト (ウィンドウやワーカー) では、後に setTimeout()setInterval() を呼び出しても タイムアウト ID を再使用しないことが保証されています。ただし、別なオブジェクトでは別の ID プールを使用します。

- -

- -

以下の例はウェブページに 2 つのシンプルなボタンを置いており、setTimeout() および clearTimeout() のルーチンを実行します。1 番目のボタンを押下すると 2 秒後にアラートダイアログを呼び出すタイムアウトを設定して、clearTimeout() で使用するタイムアウト ID を保存します。2 番目のボタンを押下すると、このタイムアウトをキャンセルできます。

- -

HTML

- -
<p>Live Example</p>
-<button onclick="delayedAlert();">2秒後にアラートボックスを表示する</button>
-<p></p>
-<button onclick="clearAlert();">アラートを事前にキャンセルする</button>
-
- -

JavaScript

- -
var timeoutID;
-
-function delayedAlert() {
-  timeoutID = window.setTimeout(window.alert, 2*1000, '本当に遅い!');
-}
-
-function clearAlert() {
-  window.clearTimeout(timeoutID);
-}
-
- -

結果

- -

{{EmbedLiveSample('Example')}}

- -

clearTimeout() の例 もご覧ください。

- -

ポリフィル

- -

コールバック関数に 1 つ以上の引数を渡す必要があるが、setTimeout()setInterval() を使用して追加の引数を渡す機能に対応していないブラウザー (例えば Internet Explorer 9 以前) で動作しなければならない場合は、HTML5 標準の引数渡し機能を可能にする以下のポリフィルを追加するとよいでしょう。このコードをスクリプトの先頭に追加してください。

- -
/*\
-|*|
-|*|  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[, arg1, arg2, ...]);
-|*|  var timeoutID = window.setTimeout(code, delay);
-|*|  var intervalID = window.setInterval(func, delay[, arg1, arg2, ...]);
-|*|  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 限定の修正

- -

IE 9 およびそれ以前を含む、他のすべてのモバイルブラウザーやデスクトップブラウザーで完全に目立たない修正が必要である場合は、以下の 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);
-
- -

さらに、関数の bind を使用する方法もあります。例:

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

"this" 問題

- -

setTimeout() にメソッド (そういうことならほかの関数も) を渡すとき、コードが実行される際の this の値が想定とは異なるかもしれません。この問題は JavaScript リファレンス でより詳細に説明されています。

- -

説明

- -

setTimeout() によって実行されるコードは、 setTimeout が呼び出された関数とは別の実行コンテキスト内から呼び出されます。呼び出された関数に this キーワードを設定する通常の規則を適用して、呼び出しあるいは bindthis を設定しなければ、非 strict モードでは global (または window)、strict モードでは undefined になります。これは、setTimeout が呼び出された関数の this 値と同じにはなりません。

- -
-

注: setTimeout コールバックの既定の this の値は、厳格モードであっても undefined ではなく、 window オブジェクトです。

-
- -

以下の例をご覧ください。

- -
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"
- -

myMethod を呼び出したときに、呼び出しによって thismyArray に設定されますので、関数内で this[sProperty]myArray[sProperty] と等価です。しかし、以下のコードでは動作が異なります。

- -
setTimeout(myArray.myMethod, 1.0*1000); // 1秒後に "[object Window]" と表示
-setTimeout(myArray.myMethod, 1.5*1000, '1'); // 1.5秒後に "undefined" と表示
- -

myArray.myMethod 関数を setTimeout に渡しており、関数が呼び出されると this が前のように設定されず、既定値の window オブジェクトになります。Array の forEach や reduce などのメソッドにあるような、thisArg を setTimeout に渡すオプションもありません。また以下のように、this を設定するために call を使用する方法も動作しません。

- -
setTimeout.call(myArray, myArray.myMethod, 2.0*1000); // error: "NS_ERROR_XPC_BAD_OP_ON_WN_PROTO: Illegal operation on WrappedNative prototype object"
-setTimeout.call(myArray, myArray.myMethod, 2.5*1000, 2); // same error
-
- -

考えられる解決策

- -

この問題の一般的な解決策は、this に必要な値を設定するラッパー関数を使用することです:

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

代わりにアロー関数も使用できます。

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

他に考えられる "this" 問題の解決策として、本来の setTimeout() および setInterval() グローバル関数を、this オブジェクトを渡せるようにして、コールバックで Function.prototype.call を使用して設定するように置き換える方法があります。例えば:

- -
// Enable setting 'this' in 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);
-};
- -
: これら 2 つの置き換えにより、IE のタイマーで HTML5 標準の、コールバック関数に任意の引数を渡すことも可能になります。よって、ポリフィルとしても使用できます。Callback arguments の節をご覧ください。
- -

新機能のテスト:

- -
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, 2.0*1000); // prints "zero,one,two" after 2 seconds
-setTimeout.call(myArray, myArray.myMethod, 2.5*1000, 2); // prints "two" after 2.5 seconds
-
- -
: JavaScript 1.8.5 で、関数のすべての呼び出しに対して this の値を設定する Function.prototype.bind() メソッドを導入しました。これにより、コールバックで this の値を設定するためにラッパー関数を使用しなければならない状況を回避できます。
- -

bind() の使用例:

- -
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, 1.0*1000); // still prints "zero,one,two" after 1 second because of the binding
-setTimeout(myBoundMethod, 1.5*1000, "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()")}} がコールバックのネスト (ネストの深さが少なくとも数段階ある) によって連続的に呼び出された、あるいは連続的なインターバルが数回発生した後に呼び出されたときに、少なくとも 4 ミリ秒ごとに呼び出されるように制限をかけます。例えば:

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

Chrome および Firefox では、5 回目の連続的なコールバックの呼び出しで制限をかけます。また Safar は 6 回目、Edge は 3 回目で制限をかけます。Gecko は バージョン 56 で、setInterval() で制限を始めました (後述のとおり setTimeout() は以前から行っていました)。

- -

歴史的に 一部のブラウザー (例えば Firefox) は、あらゆる場所から呼び出された setInterval()、あるいはネストの深さが少なくとも数段階ある setTimeout() が呼び出されたときの制限を、若干異なる動作で実装しています。。

- -

0 ms タイマーをモダンブラウザーで実装するには、ここで説明されている {{domxref("window.postMessage()")}} を利用できます。

- -
-

: 最小遅延である DOM_MIN_TIMEOUT_VALUE は 4 ms (Firefox の dom.min_timeout_value の設定に保存されています) であり、DOM_CLAMP_TIMEOUT_NESTING_LEVEL は 5 です。

-
- -
-

: 4 ms は HTML5 の仕様で標準化されています。 そして、2010 年以降にリリースされたブラウザー間で一貫しています。{{geckoRelease("5.0")}} 以前では、ネストされた setTimeout の最小値は 10 ms でした。

-
- -

非アクティブタブのタイムアウトは 1000 ms 以上に制限される

- -

バックグラウンドのタブによる負荷 (およびバッテリー消費) を軽減するため、アクティブ状態でないタブでのタイマーの呼び出しは、1 秒 (1,000 ms) あたり 1 回までとなります。

- -

Firefox はこの動作をバージョン 5 ({{bug(633421)}} を参照。1000 ms の定数は設定項目 dom.min_background_timeout_value で変更できます) から、Chrome はこの動作をバージョン 11 (crbug.com/66078) から実装しています。

- -

Android 版 Firefox は {{bug(736602)}} によって、 Firefox 14 からバックグラウンドタブで 15 分のタイムアウト値を使用しており、またバックグラウンドタブを完全にアンロードすることもできます。

- -
-

Firefox 50 では、 Web Audio API の {{domxref("AudioContext")}} が音声を再生中であればバックグラウンドタブの制限を行いません。さらに Firefox 51 では、音声を再生していなくても {{domxref("AudioContext")}} を提供していれば、バックグラウンドタブの制限を行わないように改良しました。これによりタブがバックグラウンドであるときに、楽譜を基に音楽を再生するアプリで拍子が合わない、あるいは音楽が正しく同期しないといった問題が解決します。

-
- -

トラッキングスクリプトのタイムアウトを制限する

- -

Firefox 55 より、トラッキングスクリプト (例えば Google Analytics や、TP リスト によって Firefox がトラッキングスクリプトであると認識するスクリプトの URL) にさらなる制限を課します。フォアグラウンドで実行しているとき、最小遅延の制限は 4ms のままです。しかしバックグラウンドのタブでは、最小遅延を 10,000ms または 10 秒に制限します。これはドキュメントが最初に読み込まれてから 30 秒後に発効します。

- -

この動作を制御する設定項目は以下のとおりです。

- - - -

タイムアウトの遅延

- -

前出の "制限" に加えて、ページ内 (またはOSやブラウザー自身) の他のタスクの処理に時間がかかると、タイムアウトは遅れます。注目すべき重要なケースとして、setTimeout() を呼び出したスレッドが終了するまで関数やコードスニペットを実行できないことが挙げられます。例えば:

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

このコードは、コンソールへ以下のように出力します。

- -
After setTimeout
-foo has been called
- -

これは setTimeout を遅延 0 で呼び出したとしても、直ちに実行するのではなくキューに載せて、次の機会に実行するようスケジューリングされるためです。現在実行中のコードはキューにある関数を実行する前に完了しなければならず、このために実行結果の順序が想定どおりにならない場合があります。

- -

WebExtension のバックグラウンドページとタイマー

- -

WebExtension のバックグラウンドページでは、タイマーが正しく動作しません。これはバックグラウンドページが実際には常にロードされたままではないからです。ブラウザ-は使用されていない場合はアンロードし、必要なときに復元することができます。これは拡張機能にはほとんど透過的ですが、いくつかのもの (JS タイマーを含む) はアンロード/リストアサイクル全体では動作しないので、バックグラウンドページは代わりにアラームを使うことを推奨します。これについての詳細は Migrate to Event Driven Background Scripts にあります。

- -

この記事の執筆時点では、 Chrome だけが上記の挙動を示していました - Firefox はまだアンロード/リストアの挙動をしていないので、タイマーは動作するでしょう。しかし、いくつかの理由から WebExtensions でタイマーを使わないようにするのはまだ良い考えです。

- -
    -
  1. Chrome との互換性のため
  2. -
  3. 将来、動作が変更された場合に問題が発生する可能性があるため
  4. -
- -

最大遅延時間

- -

Internet Explorer、Chrome、Safari、Firefox を含むブラウザーは、内部で遅延時間を 32 ビット符号付き整数値で保存します。このため 2,147,483,647 ms (約 24.8 日) より大きな遅延時間を使用すると整数値がオーバーフローして、その結果直ちに実行されるタイムアウトになります。

- -

仕様書

- - - - - - - - - - - - - - - - - - - - - -
仕様書状態備考
{{SpecName('HTML WHATWG', 'webappapis.html#dom-settimeout', 'WindowOrWorkerGlobalScope.setTimeout()')}}{{Spec2("HTML WHATWG")}}最新の仕様で、メソッドを WindowOrWorkerGlobalScope ミックスインに移動。
{{SpecName("HTML WHATWG", "webappapis.html#dom-settimeout", "WindowTimers.setTimeout()")}}{{Spec2("HTML WHATWG")}}初回定義 (DOM Level 0)
- -

ブラウザーの互換性

- -

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

- -

関連情報

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