From 1e5ef69352fca974bc2c3b0c507b20c97189fd1e Mon Sep 17 00:00:00 2001 From: MDN Date: Sun, 22 Aug 2021 00:45:00 +0000 Subject: [CRON] sync translated content --- files/es/_wikihistory.json | 16 ++++++++-------- 1 file changed, 8 insertions(+), 8 deletions(-) (limited to 'files/es/_wikihistory.json') diff --git a/files/es/_wikihistory.json b/files/es/_wikihistory.json index 3c8ab55145..1b9437479b 100644 --- a/files/es/_wikihistory.json +++ b/files/es/_wikihistory.json @@ -10652,25 +10652,25 @@ "ulisescab" ] }, - "Web/CSS/CSS_Background_and_Borders/Border-image_generator": { + "Web/CSS/CSS_Backgrounds_and_Borders": { + "modified": "2019-03-23T22:41:48.399Z", + "contributors": [ + "teoli" + ] + }, + "Web/CSS/CSS_Backgrounds_and_Borders/Border-image_generator": { "modified": "2019-03-23T22:41:48.777Z", "contributors": [ "teoli", "mcclone2001" ] }, - "Web/CSS/CSS_Background_and_Borders/Border-radius_generator": { + "Web/CSS/CSS_Backgrounds_and_Borders/Border-radius_generator": { "modified": "2019-03-18T21:15:42.476Z", "contributors": [ "israel-munoz" ] }, - "Web/CSS/CSS_Backgrounds_and_Borders": { - "modified": "2019-03-23T22:41:48.399Z", - "contributors": [ - "teoli" - ] - }, "Web/CSS/CSS_Backgrounds_and_Borders/Using_multiple_backgrounds": { "modified": "2019-03-23T22:17:03.740Z", "contributors": [ -- cgit v1.2.3-54-g00ecf From 5d18c06cf65a281de4d382e124140f1557e67637 Mon Sep 17 00:00:00 2001 From: MDN Date: Fri, 27 Aug 2021 00:49:43 +0000 Subject: [CRON] sync translated content --- files/es/_redirects.txt | 5 +- files/es/_wikihistory.json | 18 ++-- files/es/web/api/mouseevent/pagex/index.html | 103 ++++++++++++++++++++ files/es/web/api/uievent/pagex/index.html | 102 -------------------- files/pl/_redirects.txt | 14 +-- files/pl/_wikihistory.json | 38 ++++---- files/pl/web/api/mouseevent/pagex/index.html | 18 ++++ files/pl/web/api/mouseevent/pagey/index.html | 16 ++++ files/pl/web/api/uievent/pagex/index.html | 18 ---- files/pl/web/api/uievent/pagey/index.html | 16 ---- files/zh-cn/_redirects.txt | 8 +- files/zh-cn/_wikihistory.json | 28 +++--- .../web/api/mouseevent/pagex/index.html | 106 +++++++++++++++++++++ .../web/api/mouseevent/pagey/index.html | 90 +++++++++++++++++ files/zh-cn/web/api/uievent/pagex/index.html | 105 -------------------- files/zh-cn/web/api/uievent/pagey/index.html | 89 ----------------- 16 files changed, 391 insertions(+), 383 deletions(-) create mode 100644 files/es/web/api/mouseevent/pagex/index.html delete mode 100644 files/es/web/api/uievent/pagex/index.html create mode 100644 files/pl/web/api/mouseevent/pagex/index.html create mode 100644 files/pl/web/api/mouseevent/pagey/index.html delete mode 100644 files/pl/web/api/uievent/pagex/index.html delete mode 100644 files/pl/web/api/uievent/pagey/index.html create mode 100644 files/zh-cn/conflicting/web/api/mouseevent/pagex/index.html create mode 100644 files/zh-cn/conflicting/web/api/mouseevent/pagey/index.html delete mode 100644 files/zh-cn/web/api/uievent/pagex/index.html delete mode 100644 files/zh-cn/web/api/uievent/pagey/index.html (limited to 'files/es/_wikihistory.json') diff --git a/files/es/_redirects.txt b/files/es/_redirects.txt index 76616b14f5..422cc4e36c 100644 --- a/files/es/_redirects.txt +++ b/files/es/_redirects.txt @@ -293,7 +293,7 @@ /es/docs/DOM/event.cancelable /es/docs/Web/API/Event/cancelable /es/docs/DOM/event.initEvent /es/docs/Web/API/Event/initEvent /es/docs/DOM/event.initMouseEvent /es/docs/Web/API/MouseEvent/initMouseEvent -/es/docs/DOM/event.pageX /es/docs/Web/API/UIEvent/pageX +/es/docs/DOM/event.pageX /es/docs/Web/API/MouseEvent/pageX /es/docs/DOM/event.preventDefault /es/docs/Web/API/Event/preventDefault /es/docs/DOM/event.type /es/docs/Web/API/Event/type /es/docs/DOM/form /es/docs/Web/API/HTMLFormElement @@ -360,7 +360,7 @@ /es/docs/DOM:event.cancelable /es/docs/Web/API/Event/cancelable /es/docs/DOM:event.initEvent /es/docs/Web/API/Event/initEvent /es/docs/DOM:event.initMouseEvent /es/docs/Web/API/MouseEvent/initMouseEvent -/es/docs/DOM:event.pageX /es/docs/Web/API/UIEvent/pageX +/es/docs/DOM:event.pageX /es/docs/Web/API/MouseEvent/pageX /es/docs/DOM:event.preventDefault /es/docs/Web/API/Event/preventDefault /es/docs/DOM:form /es/docs/Web/API/HTMLFormElement /es/docs/DOM:range /es/docs/Web/API/Range @@ -1566,6 +1566,7 @@ /es/docs/Web/API/Position /es/docs/Web/API/GeolocationPosition /es/docs/Web/API/RandomSource/Obtenervaloresaleatorios /es/docs/Web/API/Crypto/getRandomValues /es/docs/Web/API/SubtleCrypto/encrypt /es/docs/Web/HTTP/Headers/Digest +/es/docs/Web/API/UIEvent/pageX /es/docs/Web/API/MouseEvent/pageX /es/docs/Web/API/WebGL_API/Getting_started_with_WebGL /es/docs/Web/API/WebGL_API/Tutorial/Getting_started_with_WebGL /es/docs/Web/API/WebGL_API/Tutorial/Objetos_3D_utilizando_WebGL /es/docs/Web/API/WebGL_API/Tutorial/Creating_3D_objects_using_WebGL /es/docs/Web/API/WebGL_API/Tutorial/Wtilizando_texturas_en_WebGL /es/docs/Web/API/WebGL_API/Tutorial/Using_textures_in_WebGL diff --git a/files/es/_wikihistory.json b/files/es/_wikihistory.json index 1b9437479b..535a52b77e 100644 --- a/files/es/_wikihistory.json +++ b/files/es/_wikihistory.json @@ -7568,6 +7568,15 @@ "Mgjbot" ] }, + "Web/API/MouseEvent/pageX": { + "modified": "2019-03-23T23:12:56.756Z", + "contributors": [ + "fscholz", + "khalid32", + "Nathymig", + "Julgon" + ] + }, "Web/API/MouseEvent/shiftKey": { "modified": "2019-03-23T22:05:24.832Z", "contributors": [ @@ -8431,15 +8440,6 @@ "fscholz" ] }, - "Web/API/UIEvent/pageX": { - "modified": "2019-03-23T23:12:56.756Z", - "contributors": [ - "fscholz", - "khalid32", - "Nathymig", - "Julgon" - ] - }, "Web/API/URL": { "modified": "2019-03-23T22:19:12.735Z", "contributors": [ diff --git a/files/es/web/api/mouseevent/pagex/index.html b/files/es/web/api/mouseevent/pagex/index.html new file mode 100644 index 0000000000..7eca1c67bb --- /dev/null +++ b/files/es/web/api/mouseevent/pagex/index.html @@ -0,0 +1,103 @@ +--- +title: event.pageX +slug: Web/API/MouseEvent/pageX +tags: + - DOM + - Referencia_DOM_de_Gecko + - Todas_las_Categorías +translation_of: Web/API/UIEvent/pageX +original_slug: Web/API/UIEvent/pageX +--- +

{{ ApiRef() }}

+

Sumario

+

Retorna la coordena horizontal del evento, relativo al documento completo.

+

Sintaxis

+
pageX =event.pageX;
+
+

pageX es un valor entero expresado en pixels para la corrdenada X del puntero del ratón, relativo al documento entero, cuando se produjo el evento. Esta propiedad toma en cuenta la barra de desplazamiento horizontal de la página.

+

Ejemplo

+
<html>
+<head>
+<title>pageX\pageY & layerX\layerY example</title>
+
+<script type="text/javascript">
+
+function showCoords(evt){
+  var form = document.forms.form_coords;
+  var parent_id = evt.target.parentNode.id;
+  form.parentId.value = parent_id;
+  form.pageXCoords.value = evt.pageX;
+  form.pageYCoords.value = evt.pageY;
+  form.layerXCoords.value = evt.layerX;
+  form.layerYCoords.value = evt.layerY;
+}
+
+</script>
+
+<style type="text/css">
+
+ #d1 {
+  border: solid blue 1px;
+  padding: 20px;
+ }
+
+ #d2 {
+  position: absolute;
+  top: 180px;
+  left: 80%;
+  right:auto;
+  width: 40%;
+  border: solid blue 1px;
+  padding: 20px;
+ }
+
+ #d3 {
+  position: absolute;
+  top: 240px;
+  left: 20%;
+  width: 50%;
+  border: solid blue 1px;
+  padding: 10px;
+ }
+
+</style>
+</head>
+
+<body onmousedown="showCoords(event)">
+
+<p>To display the mouse coordinates please click anywhere on the page.</p>
+
+<div id="d1">
+<span>This is an un-positioned div so clicking it will return
+layerX/layerY values almost the same as pageX/PageY values.</span>
+</div>
+
+<div id="d2">
+<span>This is a positioned div so clicking it will return layerX/layerY
+values that are relative to the top-left corner of this positioned
+element. Note the pageX\pageY properties still return the
+absolute position in the document, including page scrolling.</span>
+
+<span>Make the page scroll more! This is a positioned div so clicking it
+will return layerX/layerY values that are relative to the top-left
+corner of this positioned element. Note the pageX\pageY properties still
+return the absolute position in the document, including page
+scrolling.</span>
+</div>
+
+<div id="d3">
+<form name="form_coords">
+ Parent Element id: <input type="text" name="parentId" size="7" /><br />
+ pageX:<input type="text" name="pageXCoords" size="7" />
+ pageY:<input type="text" name="pageYCoords" size="7" /><br />
+ layerX:<input type="text" name="layerXCoords" size="7" />
+ layerY:<input type="text" name="layerYCoords" size="7" />
+</form>
+</div>
+
+</body>
+</html>
+
+

Specificación

+

No es parte del estándar público.

+

{{ languages( { "pl": "pl/DOM/event.pageX", "en": "en/DOM/event.pageX" } ) }}

diff --git a/files/es/web/api/uievent/pagex/index.html b/files/es/web/api/uievent/pagex/index.html deleted file mode 100644 index fbd75e26f8..0000000000 --- a/files/es/web/api/uievent/pagex/index.html +++ /dev/null @@ -1,102 +0,0 @@ ---- -title: event.pageX -slug: Web/API/UIEvent/pageX -tags: - - DOM - - Referencia_DOM_de_Gecko - - Todas_las_Categorías -translation_of: Web/API/UIEvent/pageX ---- -

{{ ApiRef() }}

-

Sumario

-

Retorna la coordena horizontal del evento, relativo al documento completo.

-

Sintaxis

-
pageX =event.pageX;
-
-

pageX es un valor entero expresado en pixels para la corrdenada X del puntero del ratón, relativo al documento entero, cuando se produjo el evento. Esta propiedad toma en cuenta la barra de desplazamiento horizontal de la página.

-

Ejemplo

-
<html>
-<head>
-<title>pageX\pageY & layerX\layerY example</title>
-
-<script type="text/javascript">
-
-function showCoords(evt){
-  var form = document.forms.form_coords;
-  var parent_id = evt.target.parentNode.id;
-  form.parentId.value = parent_id;
-  form.pageXCoords.value = evt.pageX;
-  form.pageYCoords.value = evt.pageY;
-  form.layerXCoords.value = evt.layerX;
-  form.layerYCoords.value = evt.layerY;
-}
-
-</script>
-
-<style type="text/css">
-
- #d1 {
-  border: solid blue 1px;
-  padding: 20px;
- }
-
- #d2 {
-  position: absolute;
-  top: 180px;
-  left: 80%;
-  right:auto;
-  width: 40%;
-  border: solid blue 1px;
-  padding: 20px;
- }
-
- #d3 {
-  position: absolute;
-  top: 240px;
-  left: 20%;
-  width: 50%;
-  border: solid blue 1px;
-  padding: 10px;
- }
-
-</style>
-</head>
-
-<body onmousedown="showCoords(event)">
-
-<p>To display the mouse coordinates please click anywhere on the page.</p>
-
-<div id="d1">
-<span>This is an un-positioned div so clicking it will return
-layerX/layerY values almost the same as pageX/PageY values.</span>
-</div>
-
-<div id="d2">
-<span>This is a positioned div so clicking it will return layerX/layerY
-values that are relative to the top-left corner of this positioned
-element. Note the pageX\pageY properties still return the
-absolute position in the document, including page scrolling.</span>
-
-<span>Make the page scroll more! This is a positioned div so clicking it
-will return layerX/layerY values that are relative to the top-left
-corner of this positioned element. Note the pageX\pageY properties still
-return the absolute position in the document, including page
-scrolling.</span>
-</div>
-
-<div id="d3">
-<form name="form_coords">
- Parent Element id: <input type="text" name="parentId" size="7" /><br />
- pageX:<input type="text" name="pageXCoords" size="7" />
- pageY:<input type="text" name="pageYCoords" size="7" /><br />
- layerX:<input type="text" name="layerXCoords" size="7" />
- layerY:<input type="text" name="layerYCoords" size="7" />
-</form>
-</div>
-
-</body>
-</html>
-
-

Specificación

-

No es parte del estándar público.

-

{{ languages( { "pl": "pl/DOM/event.pageX", "en": "en/DOM/event.pageX" } ) }}

diff --git a/files/pl/_redirects.txt b/files/pl/_redirects.txt index e993e7fb5d..22537b5644 100644 --- a/files/pl/_redirects.txt +++ b/files/pl/_redirects.txt @@ -399,8 +399,8 @@ /pl/docs/DOM/event.layerX /pl/docs/Web/API/UIEvent/layerX /pl/docs/DOM/event.layerY /pl/docs/Web/API/UIEvent/layerY /pl/docs/DOM/event.metaKey /pl/docs/Web/API/MouseEvent/metaKey -/pl/docs/DOM/event.pageX /pl/docs/Web/API/UIEvent/pageX -/pl/docs/DOM/event.pageY /pl/docs/Web/API/UIEvent/pageY +/pl/docs/DOM/event.pageX /pl/docs/Web/API/MouseEvent/pageX +/pl/docs/DOM/event.pageY /pl/docs/Web/API/MouseEvent/pageY /pl/docs/DOM/event.relatedTarget /pl/docs/Web/API/MouseEvent/relatedTarget /pl/docs/DOM/event.screenX /pl/docs/Web/API/MouseEvent/screenX /pl/docs/DOM/event.screenY /pl/docs/Web/API/MouseEvent/screenY @@ -633,8 +633,8 @@ /pl/docs/DOM:event.layerX /pl/docs/Web/API/UIEvent/layerX /pl/docs/DOM:event.layerY /pl/docs/Web/API/UIEvent/layerY /pl/docs/DOM:event.metaKey /pl/docs/Web/API/MouseEvent/metaKey -/pl/docs/DOM:event.pageX /pl/docs/Web/API/UIEvent/pageX -/pl/docs/DOM:event.pageY /pl/docs/Web/API/UIEvent/pageY +/pl/docs/DOM:event.pageX /pl/docs/Web/API/MouseEvent/pageX +/pl/docs/DOM:event.pageY /pl/docs/Web/API/MouseEvent/pageY /pl/docs/DOM:event.relatedTarget /pl/docs/Web/API/MouseEvent/relatedTarget /pl/docs/DOM:event.screenX /pl/docs/Web/API/MouseEvent/screenX /pl/docs/DOM:event.screenY /pl/docs/Web/API/MouseEvent/screenY @@ -1456,8 +1456,8 @@ /pl/docs/Web/API/Event/layerX /pl/docs/Web/API/UIEvent/layerX /pl/docs/Web/API/Event/layerY /pl/docs/Web/API/UIEvent/layerY /pl/docs/Web/API/Event/metaKey /pl/docs/Web/API/MouseEvent/metaKey -/pl/docs/Web/API/Event/pageX /pl/docs/Web/API/UIEvent/pageX -/pl/docs/Web/API/Event/pageY /pl/docs/Web/API/UIEvent/pageY +/pl/docs/Web/API/Event/pageX /pl/docs/Web/API/MouseEvent/pageX +/pl/docs/Web/API/Event/pageY /pl/docs/Web/API/MouseEvent/pageY /pl/docs/Web/API/Event/relatedTarget /pl/docs/Web/API/MouseEvent/relatedTarget /pl/docs/Web/API/Event/screenX /pl/docs/Web/API/MouseEvent/screenX /pl/docs/Web/API/Event/screenY /pl/docs/Web/API/MouseEvent/screenY @@ -1499,6 +1499,8 @@ /pl/docs/Web/API/Stylesheet/cssRules /pl/docs/Web/API/CSSRuleList /pl/docs/Web/API/Stylesheet/deleteRule /pl/docs/Web/API/CSSStyleSheet/deleteRule /pl/docs/Web/API/Stylesheet/insertRule /pl/docs/Web/API/CSSStyleSheet/insertRule +/pl/docs/Web/API/UIEvent/pageX /pl/docs/Web/API/MouseEvent/pageX +/pl/docs/Web/API/UIEvent/pageY /pl/docs/Web/API/MouseEvent/pageY /pl/docs/Web/API/Window/clearInterval /pl/docs/Web/API/WindowOrWorkerGlobalScope/clearInterval /pl/docs/Web/API/Window/clearTimeout /pl/docs/Web/API/WindowOrWorkerGlobalScope/clearTimeout /pl/docs/Web/API/Window/onload /pl/docs/Web/API/GlobalEventHandlers/onload diff --git a/files/pl/_wikihistory.json b/files/pl/_wikihistory.json index 6ca2ddb0bc..e9f31f291a 100644 --- a/files/pl/_wikihistory.json +++ b/files/pl/_wikihistory.json @@ -2916,6 +2916,25 @@ "Ptak82" ] }, + "Web/API/MouseEvent/pageX": { + "modified": "2019-03-23T23:42:37.418Z", + "contributors": [ + "teoli", + "khalid32", + "Mgjbot", + "Jan Dudek", + "Ptak82" + ] + }, + "Web/API/MouseEvent/pageY": { + "modified": "2019-03-23T23:41:13.568Z", + "contributors": [ + "teoli", + "khalid32", + "Jan Dudek", + "Ptak82" + ] + }, "Web/API/MouseEvent/relatedTarget": { "modified": "2019-03-23T23:41:15.246Z", "contributors": [ @@ -3535,25 +3554,6 @@ "Ptak82" ] }, - "Web/API/UIEvent/pageX": { - "modified": "2019-03-23T23:42:37.418Z", - "contributors": [ - "teoli", - "khalid32", - "Mgjbot", - "Jan Dudek", - "Ptak82" - ] - }, - "Web/API/UIEvent/pageY": { - "modified": "2019-03-23T23:41:13.568Z", - "contributors": [ - "teoli", - "khalid32", - "Jan Dudek", - "Ptak82" - ] - }, "Web/API/UIEvent/view": { "modified": "2019-03-23T23:41:50.711Z", "contributors": [ diff --git a/files/pl/web/api/mouseevent/pagex/index.html b/files/pl/web/api/mouseevent/pagex/index.html new file mode 100644 index 0000000000..85e5636964 --- /dev/null +++ b/files/pl/web/api/mouseevent/pagex/index.html @@ -0,0 +1,18 @@ +--- +title: event.pageX +slug: Web/API/MouseEvent/pageX +tags: + - DOM + - Dokumentacja_Gecko_DOM + - Gecko + - Wszystkie_kategorie +translation_of: Web/API/UIEvent/pageX +original_slug: Web/API/UIEvent/pageX +--- +

{{ ApiRef() }}

+

Podsumowanie

+

Zwraca poziomą współrzędną miejsca, gdzie wystąpiło zdarzenie, względem całej strony.

+

Składnia

+
liczba = event.pageX
+
+

{{ languages( { "en": "en/DOM/event.pageX", "es": "es/DOM/event.pageX" } ) }}

diff --git a/files/pl/web/api/mouseevent/pagey/index.html b/files/pl/web/api/mouseevent/pagey/index.html new file mode 100644 index 0000000000..a001ec316d --- /dev/null +++ b/files/pl/web/api/mouseevent/pagey/index.html @@ -0,0 +1,16 @@ +--- +title: event.pageY +slug: Web/API/MouseEvent/pageY +tags: + - DOM + - Wszystkie_kategorie +translation_of: Web/API/UIEvent/pageY +original_slug: Web/API/UIEvent/pageY +--- +

{{ ApiRef() }}

+

Podsumowanie

+

Zwraca pionową współrzędną miejsca, gdzie wystąpiło zdarzenie, względem całej strony.

+

Składnia

+
liczba = event.pageY
+
+

{{ languages( { "en": "en/DOM/event.pageY" } ) }}

diff --git a/files/pl/web/api/uievent/pagex/index.html b/files/pl/web/api/uievent/pagex/index.html deleted file mode 100644 index 05b33b7b84..0000000000 --- a/files/pl/web/api/uievent/pagex/index.html +++ /dev/null @@ -1,18 +0,0 @@ ---- -title: event.pageX -slug: Web/API/UIEvent/pageX -tags: - - DOM - - Dokumentacja_Gecko_DOM - - Gecko - - Wszystkie_kategorie -translation_of: Web/API/UIEvent/pageX -original_slug: Web/API/Event/pageX ---- -

{{ ApiRef() }}

-

Podsumowanie

-

Zwraca poziomą współrzędną miejsca, gdzie wystąpiło zdarzenie, względem całej strony.

-

Składnia

-
liczba = event.pageX
-
-

{{ languages( { "en": "en/DOM/event.pageX", "es": "es/DOM/event.pageX" } ) }}

diff --git a/files/pl/web/api/uievent/pagey/index.html b/files/pl/web/api/uievent/pagey/index.html deleted file mode 100644 index e1749273da..0000000000 --- a/files/pl/web/api/uievent/pagey/index.html +++ /dev/null @@ -1,16 +0,0 @@ ---- -title: event.pageY -slug: Web/API/UIEvent/pageY -tags: - - DOM - - Wszystkie_kategorie -translation_of: Web/API/UIEvent/pageY -original_slug: Web/API/Event/pageY ---- -

{{ ApiRef() }}

-

Podsumowanie

-

Zwraca pionową współrzędną miejsca, gdzie wystąpiło zdarzenie, względem całej strony.

-

Składnia

-
liczba = event.pageY
-
-

{{ languages( { "en": "en/DOM/event.pageY" } ) }}

diff --git a/files/zh-cn/_redirects.txt b/files/zh-cn/_redirects.txt index f89f0c699c..3e3a29ee8d 100644 --- a/files/zh-cn/_redirects.txt +++ b/files/zh-cn/_redirects.txt @@ -412,7 +412,7 @@ /zh-CN/docs/DOM/event.defaultPrevented /zh-CN/docs/Web/API/Event/defaultPrevented /zh-CN/docs/DOM/event.isChar /zh-CN/docs/Web/API/UIEvent/isChar /zh-CN/docs/DOM/event.isTrusted /zh-CN/docs/Web/API/Event/isTrusted -/zh-CN/docs/DOM/event.pageY /zh-CN/docs/Web/API/UIEvent/pageY +/zh-CN/docs/DOM/event.pageY /zh-CN/docs/conflicting/Web/API/MouseEvent/pageY /zh-CN/docs/DOM/event.preventDefault /zh-CN/docs/Web/API/Event/preventDefault /zh-CN/docs/DOM/event.stopImmediatePropagation /zh-CN/docs/Web/API/Event/stopImmediatePropagation /zh-CN/docs/DOM/event.stopPropagation /zh-CN/docs/Web/API/Event/stopPropagation @@ -1309,7 +1309,7 @@ /zh-CN/docs/Web/API/Element/removeAttributre /zh-CN/docs/Web/API/Element/removeAttribute /zh-CN/docs/Web/API/Event/CustomEvent /zh-CN/docs/Web/API/CustomEvent /zh-CN/docs/Web/API/Event/isChar /zh-CN/docs/Web/API/UIEvent/isChar -/zh-CN/docs/Web/API/Event/pageY /zh-CN/docs/Web/API/UIEvent/pageY +/zh-CN/docs/Web/API/Event/pageY /zh-CN/docs/conflicting/Web/API/MouseEvent/pageY /zh-CN/docs/Web/API/Event/禁用时间冒泡 /zh-CN/docs/Web/API/Event/cancelBubble /zh-CN/docs/Web/API/EventTarget.dispatchEvent /zh-CN/docs/Web/API/EventTarget/dispatchEvent /zh-CN/docs/Web/API/EventTarget.removeEventListener /zh-CN/docs/Web/API/EventTarget/removeEventListener @@ -1476,6 +1476,8 @@ /zh-CN/docs/Web/API/Touch.screenX /zh-CN/docs/Web/API/Touch/screenX /zh-CN/docs/Web/API/Touch.screenY /zh-CN/docs/Web/API/Touch/screenY /zh-CN/docs/Web/API/TouchEvent.changedTouches /zh-CN/docs/Web/API/TouchEvent/changedTouches +/zh-CN/docs/Web/API/UIEvent/pageX /zh-CN/docs/conflicting/Web/API/MouseEvent/pageX +/zh-CN/docs/Web/API/UIEvent/pageY /zh-CN/docs/conflicting/Web/API/MouseEvent/pageY /zh-CN/docs/Web/API/UIEvent/视图 /zh-CN/docs/Web/API/UIEvent/view /zh-CN/docs/Web/API/URL.URL /zh-CN/docs/Web/API/URL/URL /zh-CN/docs/Web/API/URL.createObjectURL /zh-CN/docs/Web/API/URL/createObjectURL @@ -1629,7 +1631,7 @@ /zh-CN/docs/Web/API/event.defaultPrevented /zh-CN/docs/Web/API/Event/defaultPrevented /zh-CN/docs/Web/API/event.isChar /zh-CN/docs/Web/API/UIEvent/isChar /zh-CN/docs/Web/API/event.isTrusted /zh-CN/docs/Web/API/Event/isTrusted -/zh-CN/docs/Web/API/event.pageY /zh-CN/docs/Web/API/UIEvent/pageY +/zh-CN/docs/Web/API/event.pageY /zh-CN/docs/conflicting/Web/API/MouseEvent/pageY /zh-CN/docs/Web/API/event.preventDefault /zh-CN/docs/Web/API/Event/preventDefault /zh-CN/docs/Web/API/event.stopImmediatePropagation /zh-CN/docs/Web/API/Event/stopImmediatePropagation /zh-CN/docs/Web/API/event.stopPropagation /zh-CN/docs/Web/API/Event/stopPropagation diff --git a/files/zh-cn/_wikihistory.json b/files/zh-cn/_wikihistory.json index 5b8e48f2d8..fe36d86467 100644 --- a/files/zh-cn/_wikihistory.json +++ b/files/zh-cn/_wikihistory.json @@ -20815,20 +20815,6 @@ "jsx" ] }, - "Web/API/UIEvent/pageX": { - "modified": "2019-03-23T22:51:51.935Z", - "contributors": [ - "Tienyz" - ] - }, - "Web/API/UIEvent/pageY": { - "modified": "2019-03-24T00:16:10.292Z", - "contributors": [ - "ziyunfei", - "teoli", - "khalid32" - ] - }, "Web/API/UIEvent/view": { "modified": "2020-10-15T22:25:09.871Z", "contributors": [ @@ -47261,6 +47247,20 @@ "AshfaqHossain" ] }, + "conflicting/Web/API/MouseEvent/pageX": { + "modified": "2019-03-23T22:51:51.935Z", + "contributors": [ + "Tienyz" + ] + }, + "conflicting/Web/API/MouseEvent/pageY": { + "modified": "2019-03-24T00:16:10.292Z", + "contributors": [ + "ziyunfei", + "teoli", + "khalid32" + ] + }, "conflicting/Web/API/MouseEvent/relatedTarget": { "modified": "2019-03-23T23:09:12.340Z", "contributors": [ diff --git a/files/zh-cn/conflicting/web/api/mouseevent/pagex/index.html b/files/zh-cn/conflicting/web/api/mouseevent/pagex/index.html new file mode 100644 index 0000000000..7089c102a8 --- /dev/null +++ b/files/zh-cn/conflicting/web/api/mouseevent/pagex/index.html @@ -0,0 +1,106 @@ +--- +title: UIEvent.pageX +slug: conflicting/Web/API/MouseEvent/pageX +translation_of: Web/API/UIEvent/pageX +original_slug: Web/API/UIEvent/pageX +--- +

{{APIRef("DOM Events")}} {{Non-standard_header}}

+ +

UIEvent.pageX 是只读属性,它返回相对于整个文档的水平坐标。

+ +

语法

+ +
var pos = event.pageX
+ +

示例

+ +
var pageX = event.pageX;
+ +

pageX  是鼠标事件触发时,鼠标指针相对于整个文档 X 坐标上像素点的整数值。这一属性同时也参照了页面的水平滚动距离。

+ +
<html>
+<head>
+<title>pageX\pageY & layerX\layerY example</title>
+
+<script type="text/javascript">
+
+function showCoords(evt){
+  var form = document.forms.form_coords;
+  var parent_id = evt.target.parentNode.id;
+  form.parentId.value = parent_id;
+  form.pageXCoords.value = evt.pageX;
+  form.pageYCoords.value = evt.pageY;
+  form.layerXCoords.value = evt.layerX;
+  form.layerYCoords.value = evt.layerY;
+}
+
+</script>
+
+<style type="text/css">
+
+ #d1 {
+  border: solid blue 1px;
+  padding: 20px;
+ }
+
+ #d2 {
+  position: absolute;
+  top: 180px;
+  left: 80%;
+  right:auto;
+  width: 40%;
+  border: solid blue 1px;
+  padding: 20px;
+ }
+
+ #d3 {
+  position: absolute;
+  top: 240px;
+  left: 20%;
+  width: 50%;
+  border: solid blue 1px;
+  padding: 10px;
+ }
+
+</style>
+</head>
+
+<body onmousedown="showCoords(event)">
+
+<p>To display the mouse coordinates please click anywhere on the page.</p>
+
+<div id="d1">
+<span>This is an un-positioned div so clicking it will return
+layerX/layerY values almost the same as pageX/PageY values.</span>
+</div>
+
+<div id="d2">
+<span>This is a positioned div so clicking it will return layerX/layerY
+values that are relative to the top-left corner of this positioned
+element. Note the pageX\pageY properties still return the
+absolute position in the document, including page scrolling.</span>
+
+<span>Make the page scroll more! This is a positioned div so clicking it
+will return layerX/layerY values that are relative to the top-left
+corner of this positioned element. Note the pageX\pageY properties still
+return the absolute position in the document, including page
+scrolling.</span>
+</div>
+
+<div id="d3">
+<form name="form_coords">
+ Parent Element id: <input type="text" name="parentId" size="7" /><br />
+ pageX:<input type="text" name="pageXCoords" size="7" />
+ pageY:<input type="text" name="pageYCoords" size="7" /><br />
+ layerX:<input type="text" name="layerXCoords" size="7" />
+ layerY:<input type="text" name="layerYCoords" size="7" />
+</form>
+</div>
+
+</body>
+</html>
+
+ +

规范

+ +

这一属性不在规范中。

diff --git a/files/zh-cn/conflicting/web/api/mouseevent/pagey/index.html b/files/zh-cn/conflicting/web/api/mouseevent/pagey/index.html new file mode 100644 index 0000000000..f4c92daa4e --- /dev/null +++ b/files/zh-cn/conflicting/web/api/mouseevent/pagey/index.html @@ -0,0 +1,90 @@ +--- +title: event.pageY +slug: conflicting/Web/API/MouseEvent/pageY +translation_of: Web/API/UIEvent/pageY +original_slug: Web/API/UIEvent/pageY +--- +

{{ ApiRef() }}

+

概述

+

返回事件发生时相对于整个文档的纵坐标.

+

语法

+
var pageY = event.pageY;
+
+

pageY 是事件发生时鼠标指针所在位置相对于整个文档的纵坐标,单位为像素.该属性会考虑到页面滚动条的高度.

+

例子

+
<html>
+<head>
+<title>pageX\pageY & layerX\layerY example</title>
+
+<script type="text/javascript">
+
+function showCoords(evt){
+  var form = document.forms.form_coords;
+  var parent_id = evt.target.parentNode.id;
+  form.parentId.value = parent_id;
+  form.pageXCoords.value = evt.pageX;
+  form.pageYCoords.value = evt.pageY;
+  form.layerXCoords.value = evt.layerX;
+  form.layerYCoords.value = evt.layerY;
+}
+
+</script>
+
+<style type="text/css">
+
+ #d1 {
+  border: solid blue 1px;
+  padding: 20px;
+ }
+
+ #d2 {
+  position: absolute;
+  top: 180px;
+  left: 80%;
+  right:auto;
+  width: 40%;
+  border: solid blue 1px;
+  padding: 20px;
+ }
+
+ #d3 {
+  position: absolute;
+  top: 240px;
+  left: 20%;
+  width: 50%;
+  border: solid blue 1px;
+  padding: 10px;
+ }
+
+</style>
+</head>
+
+<body onmousedown="showCoords(event)">
+
+<p>要显示鼠标所在位置的坐标,请点击页面上的任意地方.</p>
+
+<div id="d1">
+<span>这是一个未定位的div(没有指定css position属性),所以点击它返回的layerX/layerY值几乎和pageX/PageY值完全相同.</span>
+</div>
+
+<div id="d2">
+<span>这是一个已定位的div,因此点击它时返回的layerX/layerY的值是相对于自己左上角(top-left)位置的坐标值.
+然而pageX/pageY属性返回该div在文档中绝对位置,包括页面滚动高度.</span>
+</div>
+
+<div id="d3">
+<form name="form_coords">
+ 父元素id: <input type="text" name="parentId" size="7" /><br />
+ pageX:<input type="text" name="pageXCoords" size="7" />
+ pageY:<input type="text" name="pageYCoords" size="7" /><br />
+ layerX:<input type="text" name="layerXCoords" size="7" />
+ layerY:<input type="text" name="layerYCoords" size="7" />
+</form>
+</div>
+
+</body>
+</html>
+
+

规范

+

不属于任何公开的标准.

+

{{ languages( {"pl": "pl/DOM/event.pageY","en": "en/DOM/event.pageY" } ) }}

diff --git a/files/zh-cn/web/api/uievent/pagex/index.html b/files/zh-cn/web/api/uievent/pagex/index.html deleted file mode 100644 index b4a7f812f7..0000000000 --- a/files/zh-cn/web/api/uievent/pagex/index.html +++ /dev/null @@ -1,105 +0,0 @@ ---- -title: UIEvent.pageX -slug: Web/API/UIEvent/pageX -translation_of: Web/API/UIEvent/pageX ---- -

{{APIRef("DOM Events")}} {{Non-standard_header}}

- -

UIEvent.pageX 是只读属性,它返回相对于整个文档的水平坐标。

- -

语法

- -
var pos = event.pageX
- -

示例

- -
var pageX = event.pageX;
- -

pageX  是鼠标事件触发时,鼠标指针相对于整个文档 X 坐标上像素点的整数值。这一属性同时也参照了页面的水平滚动距离。

- -
<html>
-<head>
-<title>pageX\pageY & layerX\layerY example</title>
-
-<script type="text/javascript">
-
-function showCoords(evt){
-  var form = document.forms.form_coords;
-  var parent_id = evt.target.parentNode.id;
-  form.parentId.value = parent_id;
-  form.pageXCoords.value = evt.pageX;
-  form.pageYCoords.value = evt.pageY;
-  form.layerXCoords.value = evt.layerX;
-  form.layerYCoords.value = evt.layerY;
-}
-
-</script>
-
-<style type="text/css">
-
- #d1 {
-  border: solid blue 1px;
-  padding: 20px;
- }
-
- #d2 {
-  position: absolute;
-  top: 180px;
-  left: 80%;
-  right:auto;
-  width: 40%;
-  border: solid blue 1px;
-  padding: 20px;
- }
-
- #d3 {
-  position: absolute;
-  top: 240px;
-  left: 20%;
-  width: 50%;
-  border: solid blue 1px;
-  padding: 10px;
- }
-
-</style>
-</head>
-
-<body onmousedown="showCoords(event)">
-
-<p>To display the mouse coordinates please click anywhere on the page.</p>
-
-<div id="d1">
-<span>This is an un-positioned div so clicking it will return
-layerX/layerY values almost the same as pageX/PageY values.</span>
-</div>
-
-<div id="d2">
-<span>This is a positioned div so clicking it will return layerX/layerY
-values that are relative to the top-left corner of this positioned
-element. Note the pageX\pageY properties still return the
-absolute position in the document, including page scrolling.</span>
-
-<span>Make the page scroll more! This is a positioned div so clicking it
-will return layerX/layerY values that are relative to the top-left
-corner of this positioned element. Note the pageX\pageY properties still
-return the absolute position in the document, including page
-scrolling.</span>
-</div>
-
-<div id="d3">
-<form name="form_coords">
- Parent Element id: <input type="text" name="parentId" size="7" /><br />
- pageX:<input type="text" name="pageXCoords" size="7" />
- pageY:<input type="text" name="pageYCoords" size="7" /><br />
- layerX:<input type="text" name="layerXCoords" size="7" />
- layerY:<input type="text" name="layerYCoords" size="7" />
-</form>
-</div>
-
-</body>
-</html>
-
- -

规范

- -

这一属性不在规范中。

diff --git a/files/zh-cn/web/api/uievent/pagey/index.html b/files/zh-cn/web/api/uievent/pagey/index.html deleted file mode 100644 index 6c504d3f52..0000000000 --- a/files/zh-cn/web/api/uievent/pagey/index.html +++ /dev/null @@ -1,89 +0,0 @@ ---- -title: event.pageY -slug: Web/API/UIEvent/pageY -translation_of: Web/API/UIEvent/pageY ---- -

{{ ApiRef() }}

-

概述

-

返回事件发生时相对于整个文档的纵坐标.

-

语法

-
var pageY = event.pageY;
-
-

pageY 是事件发生时鼠标指针所在位置相对于整个文档的纵坐标,单位为像素.该属性会考虑到页面滚动条的高度.

-

例子

-
<html>
-<head>
-<title>pageX\pageY & layerX\layerY example</title>
-
-<script type="text/javascript">
-
-function showCoords(evt){
-  var form = document.forms.form_coords;
-  var parent_id = evt.target.parentNode.id;
-  form.parentId.value = parent_id;
-  form.pageXCoords.value = evt.pageX;
-  form.pageYCoords.value = evt.pageY;
-  form.layerXCoords.value = evt.layerX;
-  form.layerYCoords.value = evt.layerY;
-}
-
-</script>
-
-<style type="text/css">
-
- #d1 {
-  border: solid blue 1px;
-  padding: 20px;
- }
-
- #d2 {
-  position: absolute;
-  top: 180px;
-  left: 80%;
-  right:auto;
-  width: 40%;
-  border: solid blue 1px;
-  padding: 20px;
- }
-
- #d3 {
-  position: absolute;
-  top: 240px;
-  left: 20%;
-  width: 50%;
-  border: solid blue 1px;
-  padding: 10px;
- }
-
-</style>
-</head>
-
-<body onmousedown="showCoords(event)">
-
-<p>要显示鼠标所在位置的坐标,请点击页面上的任意地方.</p>
-
-<div id="d1">
-<span>这是一个未定位的div(没有指定css position属性),所以点击它返回的layerX/layerY值几乎和pageX/PageY值完全相同.</span>
-</div>
-
-<div id="d2">
-<span>这是一个已定位的div,因此点击它时返回的layerX/layerY的值是相对于自己左上角(top-left)位置的坐标值.
-然而pageX/pageY属性返回该div在文档中绝对位置,包括页面滚动高度.</span>
-</div>
-
-<div id="d3">
-<form name="form_coords">
- 父元素id: <input type="text" name="parentId" size="7" /><br />
- pageX:<input type="text" name="pageXCoords" size="7" />
- pageY:<input type="text" name="pageYCoords" size="7" /><br />
- layerX:<input type="text" name="layerXCoords" size="7" />
- layerY:<input type="text" name="layerYCoords" size="7" />
-</form>
-</div>
-
-</body>
-</html>
-
-

规范

-

不属于任何公开的标准.

-

{{ languages( {"pl": "pl/DOM/event.pageY","en": "en/DOM/event.pageY" } ) }}

-- cgit v1.2.3-54-g00ecf 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/de/_redirects.txt | 10 +- files/de/_wikihistory.json | 32 +- files/de/web/api/btoa/index.html | 146 +++++ files/de/web/api/settimeout/index.html | 330 ++++++++++ .../api/windoworworkerglobalscope/btoa/index.html | 146 ----- .../settimeout/index.html | 330 ---------- files/es/_redirects.txt | 26 +- files/es/_wikihistory.json | 146 ++--- files/es/web/api/atob/index.html | 112 ++++ files/es/web/api/caches/index.html | 128 ++++ files/es/web/api/clearinterval/index.html | 44 ++ files/es/web/api/cleartimeout/index.html | 64 ++ files/es/web/api/createimagebitmap/index.html | 109 ++++ files/es/web/api/fetch/index.html | 178 ++++++ files/es/web/api/indexeddb/index.html | 142 +++++ files/es/web/api/issecurecontext/index.html | 87 +++ files/es/web/api/setinterval/index.html | 693 +++++++++++++++++++++ files/es/web/api/settimeout/index.html | 341 ++++++++++ .../api/windoworworkerglobalscope/atob/index.html | 112 ---- .../windoworworkerglobalscope/caches/index.html | 127 ---- .../clearinterval/index.html | 44 -- .../cleartimeout/index.html | 64 -- .../createimagebitmap/index.html | 108 ---- .../api/windoworworkerglobalscope/fetch/index.html | 177 ------ .../windoworworkerglobalscope/indexeddb/index.html | 141 ----- .../issecurecontext/index.html | 86 --- .../setinterval/index.html | 693 --------------------- .../settimeout/index.html | 341 ---------- files/fr/_redirects.txt | 49 +- files/fr/_wikihistory.json | 212 +++---- files/fr/web/api/atob/index.html | 78 +++ files/fr/web/api/btoa/index.html | 123 ++++ files/fr/web/api/caches/index.html | 80 +++ files/fr/web/api/clearinterval/index.html | 72 +++ files/fr/web/api/crossoriginisolated/index.html | 59 ++ files/fr/web/api/fetch/index.html | 194 ++++++ files/fr/web/api/indexeddb/index.html | 77 +++ files/fr/web/api/issecurecontext/index.html | 47 ++ files/fr/web/api/origin/index.html | 51 ++ files/fr/web/api/queuemicrotask/index.html | 118 ++++ files/fr/web/api/settimeout/index.html | 361 +++++++++++ .../api/windoworworkerglobalscope/atob/index.html | 78 --- .../api/windoworworkerglobalscope/btoa/index.html | 123 ---- .../windoworworkerglobalscope/caches/index.html | 79 --- .../clearinterval/index.html | 72 --- .../crossoriginisolated/index.html | 58 -- .../api/windoworworkerglobalscope/fetch/index.html | 193 ------ .../windoworworkerglobalscope/indexeddb/index.html | 76 --- .../issecurecontext/index.html | 46 -- .../windoworworkerglobalscope/origin/index.html | 50 -- .../queuemicrotask/index.html | 117 ---- .../settimeout/index.html | 360 ----------- files/ja/_redirects.txt | 76 ++- files/ja/_wikihistory.json | 260 ++++---- 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 ------------- files/ko/_redirects.txt | 3 +- files/ko/_wikihistory.json | 14 +- files/ko/web/api/settimeout/index.html | 363 +++++++++++ .../settimeout/index.html | 363 ----------- files/pl/_redirects.txt | 34 +- files/pl/_wikihistory.json | 36 +- files/pl/web/api/atob/index.html | 105 ++++ files/pl/web/api/btoa/index.html | 127 ++++ files/pl/web/api/clearinterval/index.html | 29 + files/pl/web/api/cleartimeout/index.html | 41 ++ files/pl/web/api/setinterval/index.html | 88 +++ files/pl/web/api/settimeout/index.html | 47 ++ .../api/windoworworkerglobalscope/atob/index.html | 105 ---- .../api/windoworworkerglobalscope/btoa/index.html | 127 ---- .../clearinterval/index.html | 29 - .../cleartimeout/index.html | 41 -- .../setinterval/index.html | 88 --- .../settimeout/index.html | 47 -- files/pt-br/_redirects.txt | 10 +- files/pt-br/_wikihistory.json | 54 +- files/pt-br/web/api/atob/index.html | 73 +++ files/pt-br/web/api/cleartimeout/index.html | 101 +++ files/pt-br/web/api/fetch/index.html | 306 +++++++++ files/pt-br/web/api/setinterval/index.html | 630 +++++++++++++++++++ .../api/windoworworkerglobalscope/atob/index.html | 73 --- .../cleartimeout/index.html | 101 --- .../api/windoworworkerglobalscope/fetch/index.html | 305 --------- .../setinterval/index.html | 629 ------------------- files/ru/_redirects.txt | 13 +- files/ru/_wikihistory.json | 112 ++-- files/ru/web/api/atob/index.html | 71 +++ files/ru/web/api/btoa/index.html | 94 +++ files/ru/web/api/caches/index.html | 80 +++ files/ru/web/api/cleartimeout/index.html | 95 +++ files/ru/web/api/fetch/index.html | 169 +++++ files/ru/web/api/setinterval/index.html | 642 +++++++++++++++++++ files/ru/web/api/settimeout/index.html | 261 ++++++++ .../api/windoworworkerglobalscope/atob/index.html | 70 --- .../api/windoworworkerglobalscope/btoa/index.html | 94 --- .../windoworworkerglobalscope/caches/index.html | 79 --- .../cleartimeout/index.html | 94 --- .../api/windoworworkerglobalscope/fetch/index.html | 168 ----- .../setinterval/index.html | 641 ------------------- .../settimeout/index.html | 261 -------- files/zh-cn/_redirects.txt | 54 +- files/zh-cn/_wikihistory.json | 336 +++++----- files/zh-cn/web/api/atob/index.html | 75 +++ files/zh-cn/web/api/btoa/index.html | 172 +++++ files/zh-cn/web/api/caches/index.html | 128 ++++ files/zh-cn/web/api/clearinterval/index.html | 75 +++ files/zh-cn/web/api/cleartimeout/index.html | 151 +++++ files/zh-cn/web/api/createimagebitmap/index.html | 208 +++++++ files/zh-cn/web/api/crossoriginisolated/index.html | 59 ++ files/zh-cn/web/api/fetch/index.html | 174 ++++++ files/zh-cn/web/api/indexeddb/index.html | 176 ++++++ files/zh-cn/web/api/issecurecontext/index.html | 101 +++ files/zh-cn/web/api/origin/index.html | 99 +++ files/zh-cn/web/api/queuemicrotask/index.html | 109 ++++ files/zh-cn/web/api/setinterval/index.html | 636 +++++++++++++++++++ files/zh-cn/web/api/settimeout/index.html | 477 ++++++++++++++ .../api/windoworworkerglobalscope/atob/index.html | 75 --- .../api/windoworworkerglobalscope/btoa/index.html | 172 ----- .../windoworworkerglobalscope/caches/index.html | 127 ---- .../clearinterval/index.html | 75 --- .../cleartimeout/index.html | 151 ----- .../createimagebitmap/index.html | 207 ------ .../crossoriginisolated/index.html | 58 -- .../api/windoworworkerglobalscope/fetch/index.html | 173 ----- .../windoworworkerglobalscope/indexeddb/index.html | 175 ------ .../issecurecontext/index.html | 100 --- .../windoworworkerglobalscope/origin/index.html | 98 --- .../queuemicrotask/index.html | 108 ---- .../setinterval/index.html | 636 ------------------- .../settimeout/index.html | 477 -------------- files/zh-tw/_redirects.txt | 2 + files/zh-tw/_wikihistory.json | 24 +- files/zh-tw/web/api/btoa/index.html | 137 ++++ files/zh-tw/web/api/setinterval/index.html | 628 +++++++++++++++++++ .../api/windoworworkerglobalscope/btoa/index.html | 136 ---- .../setinterval/index.html | 627 ------------------- 158 files changed, 13175 insertions(+), 13067 deletions(-) create mode 100644 files/de/web/api/btoa/index.html create mode 100644 files/de/web/api/settimeout/index.html delete mode 100644 files/de/web/api/windoworworkerglobalscope/btoa/index.html delete mode 100644 files/de/web/api/windoworworkerglobalscope/settimeout/index.html create mode 100644 files/es/web/api/atob/index.html create mode 100644 files/es/web/api/caches/index.html create mode 100644 files/es/web/api/clearinterval/index.html create mode 100644 files/es/web/api/cleartimeout/index.html create mode 100644 files/es/web/api/createimagebitmap/index.html create mode 100644 files/es/web/api/fetch/index.html create mode 100644 files/es/web/api/indexeddb/index.html create mode 100644 files/es/web/api/issecurecontext/index.html create mode 100644 files/es/web/api/setinterval/index.html create mode 100644 files/es/web/api/settimeout/index.html delete mode 100644 files/es/web/api/windoworworkerglobalscope/atob/index.html delete mode 100644 files/es/web/api/windoworworkerglobalscope/caches/index.html delete mode 100644 files/es/web/api/windoworworkerglobalscope/clearinterval/index.html delete mode 100644 files/es/web/api/windoworworkerglobalscope/cleartimeout/index.html delete mode 100644 files/es/web/api/windoworworkerglobalscope/createimagebitmap/index.html delete mode 100644 files/es/web/api/windoworworkerglobalscope/fetch/index.html delete mode 100644 files/es/web/api/windoworworkerglobalscope/indexeddb/index.html delete mode 100644 files/es/web/api/windoworworkerglobalscope/issecurecontext/index.html delete mode 100644 files/es/web/api/windoworworkerglobalscope/setinterval/index.html delete mode 100644 files/es/web/api/windoworworkerglobalscope/settimeout/index.html create mode 100644 files/fr/web/api/atob/index.html create mode 100644 files/fr/web/api/btoa/index.html create mode 100644 files/fr/web/api/caches/index.html create mode 100644 files/fr/web/api/clearinterval/index.html create mode 100644 files/fr/web/api/crossoriginisolated/index.html create mode 100644 files/fr/web/api/fetch/index.html create mode 100644 files/fr/web/api/indexeddb/index.html create mode 100644 files/fr/web/api/issecurecontext/index.html create mode 100644 files/fr/web/api/origin/index.html create mode 100644 files/fr/web/api/queuemicrotask/index.html create mode 100644 files/fr/web/api/settimeout/index.html delete mode 100644 files/fr/web/api/windoworworkerglobalscope/atob/index.html delete mode 100644 files/fr/web/api/windoworworkerglobalscope/btoa/index.html delete mode 100644 files/fr/web/api/windoworworkerglobalscope/caches/index.html delete mode 100644 files/fr/web/api/windoworworkerglobalscope/clearinterval/index.html delete mode 100644 files/fr/web/api/windoworworkerglobalscope/crossoriginisolated/index.html delete mode 100644 files/fr/web/api/windoworworkerglobalscope/fetch/index.html delete mode 100644 files/fr/web/api/windoworworkerglobalscope/indexeddb/index.html delete mode 100644 files/fr/web/api/windoworworkerglobalscope/issecurecontext/index.html delete mode 100644 files/fr/web/api/windoworworkerglobalscope/origin/index.html delete mode 100644 files/fr/web/api/windoworworkerglobalscope/queuemicrotask/index.html delete mode 100644 files/fr/web/api/windoworworkerglobalscope/settimeout/index.html 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 create mode 100644 files/ko/web/api/settimeout/index.html delete mode 100644 files/ko/web/api/windoworworkerglobalscope/settimeout/index.html create mode 100644 files/pl/web/api/atob/index.html create mode 100644 files/pl/web/api/btoa/index.html create mode 100644 files/pl/web/api/clearinterval/index.html create mode 100644 files/pl/web/api/cleartimeout/index.html create mode 100644 files/pl/web/api/setinterval/index.html create mode 100644 files/pl/web/api/settimeout/index.html delete mode 100644 files/pl/web/api/windoworworkerglobalscope/atob/index.html delete mode 100644 files/pl/web/api/windoworworkerglobalscope/btoa/index.html delete mode 100644 files/pl/web/api/windoworworkerglobalscope/clearinterval/index.html delete mode 100644 files/pl/web/api/windoworworkerglobalscope/cleartimeout/index.html delete mode 100644 files/pl/web/api/windoworworkerglobalscope/setinterval/index.html delete mode 100644 files/pl/web/api/windoworworkerglobalscope/settimeout/index.html create mode 100644 files/pt-br/web/api/atob/index.html create mode 100644 files/pt-br/web/api/cleartimeout/index.html create mode 100644 files/pt-br/web/api/fetch/index.html create mode 100644 files/pt-br/web/api/setinterval/index.html delete mode 100644 files/pt-br/web/api/windoworworkerglobalscope/atob/index.html delete mode 100644 files/pt-br/web/api/windoworworkerglobalscope/cleartimeout/index.html delete mode 100644 files/pt-br/web/api/windoworworkerglobalscope/fetch/index.html delete mode 100644 files/pt-br/web/api/windoworworkerglobalscope/setinterval/index.html create mode 100644 files/ru/web/api/atob/index.html create mode 100644 files/ru/web/api/btoa/index.html create mode 100644 files/ru/web/api/caches/index.html create mode 100644 files/ru/web/api/cleartimeout/index.html create mode 100644 files/ru/web/api/fetch/index.html create mode 100644 files/ru/web/api/setinterval/index.html create mode 100644 files/ru/web/api/settimeout/index.html delete mode 100644 files/ru/web/api/windoworworkerglobalscope/atob/index.html delete mode 100644 files/ru/web/api/windoworworkerglobalscope/btoa/index.html delete mode 100644 files/ru/web/api/windoworworkerglobalscope/caches/index.html delete mode 100644 files/ru/web/api/windoworworkerglobalscope/cleartimeout/index.html delete mode 100644 files/ru/web/api/windoworworkerglobalscope/fetch/index.html delete mode 100644 files/ru/web/api/windoworworkerglobalscope/setinterval/index.html delete mode 100644 files/ru/web/api/windoworworkerglobalscope/settimeout/index.html create mode 100644 files/zh-cn/web/api/atob/index.html create mode 100644 files/zh-cn/web/api/btoa/index.html create mode 100644 files/zh-cn/web/api/caches/index.html create mode 100644 files/zh-cn/web/api/clearinterval/index.html create mode 100644 files/zh-cn/web/api/cleartimeout/index.html create mode 100644 files/zh-cn/web/api/createimagebitmap/index.html create mode 100644 files/zh-cn/web/api/crossoriginisolated/index.html create mode 100644 files/zh-cn/web/api/fetch/index.html create mode 100644 files/zh-cn/web/api/indexeddb/index.html create mode 100644 files/zh-cn/web/api/issecurecontext/index.html create mode 100644 files/zh-cn/web/api/origin/index.html create mode 100644 files/zh-cn/web/api/queuemicrotask/index.html create mode 100644 files/zh-cn/web/api/setinterval/index.html create mode 100644 files/zh-cn/web/api/settimeout/index.html delete mode 100644 files/zh-cn/web/api/windoworworkerglobalscope/atob/index.html delete mode 100644 files/zh-cn/web/api/windoworworkerglobalscope/btoa/index.html delete mode 100644 files/zh-cn/web/api/windoworworkerglobalscope/caches/index.html delete mode 100644 files/zh-cn/web/api/windoworworkerglobalscope/clearinterval/index.html delete mode 100644 files/zh-cn/web/api/windoworworkerglobalscope/cleartimeout/index.html delete mode 100644 files/zh-cn/web/api/windoworworkerglobalscope/createimagebitmap/index.html delete mode 100644 files/zh-cn/web/api/windoworworkerglobalscope/crossoriginisolated/index.html delete mode 100644 files/zh-cn/web/api/windoworworkerglobalscope/fetch/index.html delete mode 100644 files/zh-cn/web/api/windoworworkerglobalscope/indexeddb/index.html delete mode 100644 files/zh-cn/web/api/windoworworkerglobalscope/issecurecontext/index.html delete mode 100644 files/zh-cn/web/api/windoworworkerglobalscope/origin/index.html delete mode 100644 files/zh-cn/web/api/windoworworkerglobalscope/queuemicrotask/index.html delete mode 100644 files/zh-cn/web/api/windoworworkerglobalscope/setinterval/index.html delete mode 100644 files/zh-cn/web/api/windoworworkerglobalscope/settimeout/index.html create mode 100644 files/zh-tw/web/api/btoa/index.html create mode 100644 files/zh-tw/web/api/setinterval/index.html delete mode 100644 files/zh-tw/web/api/windoworworkerglobalscope/btoa/index.html delete mode 100644 files/zh-tw/web/api/windoworworkerglobalscope/setinterval/index.html (limited to 'files/es/_wikihistory.json') diff --git a/files/de/_redirects.txt b/files/de/_redirects.txt index bb608a1e82..6a5b8a39f0 100644 --- a/files/de/_redirects.txt +++ b/files/de/_redirects.txt @@ -214,7 +214,7 @@ /de/docs/DOM/window /de/docs/Web/API/Window /de/docs/DOM/window.dump /de/docs/Web/API/Window/dump /de/docs/DOM/window.openDialog /de/docs/Web/API/Window/openDialog -/de/docs/DOM/window.setTimeout /de/docs/Web/API/WindowOrWorkerGlobalScope/setTimeout +/de/docs/DOM/window.setTimeout /de/docs/Web/API/setTimeout /de/docs/DragDrop /de/docs/Web/API/HTML_Drag_and_Drop_API /de/docs/Erweiterungen_für_Firefox_3_aktualisieren /de/docs/Mozilla/Firefox/Releases/3/Updating_extensions /de/docs/Farbverläufe_in_CSS /de/docs/Web/CSS/CSS_Images/Using_CSS_gradients @@ -447,10 +447,12 @@ /de/docs/Web/API/WebGL_API/Tutorial/Objekte_mit_WebGL_animieren /de/docs/Web/API/WebGL_API/Tutorial/Animating_objects_with_WebGL /de/docs/Web/API/WebGL_API/Tutorial/Texturen_in_WebGL_verwenden /de/docs/Web/API/WebGL_API/Tutorial/Using_textures_in_WebGL /de/docs/Web/API/Window.alert /de/docs/Web/API/Window/alert -/de/docs/Web/API/Window/setTimeout /de/docs/Web/API/WindowOrWorkerGlobalScope/setTimeout +/de/docs/Web/API/Window/setTimeout /de/docs/Web/API/setTimeout /de/docs/Web/API/WindowBase64 /de/docs/Web/API/WindowOrWorkerGlobalScope -/de/docs/Web/API/WindowBase64/btoa /de/docs/Web/API/WindowOrWorkerGlobalScope/btoa -/de/docs/Web/API/WindowTimers/setTimeout /de/docs/Web/API/WindowOrWorkerGlobalScope/setTimeout +/de/docs/Web/API/WindowBase64/btoa /de/docs/Web/API/btoa +/de/docs/Web/API/WindowOrWorkerGlobalScope/btoa /de/docs/Web/API/btoa +/de/docs/Web/API/WindowOrWorkerGlobalScope/setTimeout /de/docs/Web/API/setTimeout +/de/docs/Web/API/WindowTimers/setTimeout /de/docs/Web/API/setTimeout /de/docs/Web/API/document.documentElement /de/docs/Web/API/Document/documentElement /de/docs/Web/Barrierefreiheit /de/docs/Web/Accessibility /de/docs/Web/Barrierefreiheit/ARIA /de/docs/Web/Accessibility/ARIA diff --git a/files/de/_wikihistory.json b/files/de/_wikihistory.json index 89259bd2ca..6e9006333c 100644 --- a/files/de/_wikihistory.json +++ b/files/de/_wikihistory.json @@ -4194,22 +4194,6 @@ "teoli" ] }, - "Web/API/WindowOrWorkerGlobalScope/btoa": { - "modified": "2019-03-23T22:50:32.544Z", - "contributors": [ - "cami" - ] - }, - "Web/API/WindowOrWorkerGlobalScope/setTimeout": { - "modified": "2019-03-23T23:36:28.621Z", - "contributors": [ - "mdnde", - "Eschon", - "fscholz", - "c0ffm3k4r", - "wartab" - ] - }, "Web/API/Worker": { "modified": "2019-03-18T21:45:39.485Z", "contributors": [ @@ -4227,6 +4211,12 @@ "paul_thomann" ] }, + "Web/API/btoa": { + "modified": "2019-03-23T22:50:32.544Z", + "contributors": [ + "cami" + ] + }, "Web/API/notification": { "modified": "2019-03-23T22:55:22.604Z", "contributors": [ @@ -4243,6 +4233,16 @@ "mwsh2005" ] }, + "Web/API/setTimeout": { + "modified": "2019-03-23T23:36:28.621Z", + "contributors": [ + "mdnde", + "Eschon", + "fscholz", + "c0ffm3k4r", + "wartab" + ] + }, "Web/Accessibility": { "modified": "2019-09-09T14:09:32.470Z", "contributors": [ diff --git a/files/de/web/api/btoa/index.html b/files/de/web/api/btoa/index.html new file mode 100644 index 0000000000..62a89eac22 --- /dev/null +++ b/files/de/web/api/btoa/index.html @@ -0,0 +1,146 @@ +--- +title: WindowBase64.btoa() +slug: Web/API/btoa +tags: + - API + - Méthode + - Referenz +translation_of: Web/API/WindowOrWorkerGlobalScope/btoa +original_slug: Web/API/WindowOrWorkerGlobalScope/btoa +--- +
{{APIRef("HTML DOM")}}
+ +

Erzeugt eine Base-64-kodierten ASCII-Zeichenkette aus einer "Zeichenkette" von Binärdaten.

+ +

Hinweis: diese Funktion ist nicht für Raw-Unicode-Zeichenketten geeignet (siehe Abschnitt "Unicode-Zeichenketten" unten).

+ +

Syntax

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

Example

+ +
var encodedData = window.btoa("Hello, world"); // Zeichenkette kodieren
+var decodedData = window.atob(encodedData); // Zeichenkette dekodieren
+
+ +

Hinweise

+ +

Diese Methode kann verwendet werden, um Daten zu kodieren, übertragen, und mittels {{domxref("WindowBase64.atob","window.atob()")}} wieder zu dekodieren, welche andernfalls Übertragungsprobleme bereiten würden. Beispielsweise ist es möglich, die Steuerzeichen mit den ASCII-Werten 0 bis 31 zu kodieren.

+ +

btoa() steht auch in JavaScript implementierten XPCOM-Komponenten zur Verfügung, auch wenn window in solchen Komponenten nicht das globale Objekt ist.

+ +

Unicode-Zeichenketten

+ +

In den meisten Browsern verursacht ein Aufruf von window.btoa() mit einer Unicode-Zeichenkette eine "Character Out Of Range"-Exception ("Zeichen außerhalb des zulässigen Wertebereichs").

+ +

Das kann mithilfe eines solchen Code-Schemas vermieden werden (beigesteuert von Johan Sundström):

+ +
function utf8_to_b64(str) {
+    return window.btoa(unescape(encodeURIComponent(str)));
+}
+
+function b64_to_utf8(str) {
+    return decodeURIComponent(escape(window.atob(str)));
+}
+
+// Usage:
+utf8_to_b64('✓ à la mode'); // JTI1dTI3MTMlMjUyMCUyNUUwJTI1MjBsYSUyNTIwbW9kZQ==
+b64_to_utf8('JTI1dTI3MTMlMjUyMCUyNUUwJTI1MjBsYSUyNTIwbW9kZQ=='); // "✓ à la mode"
+
+utf8_to_b64('I \u2661 Unicode!'); // SSUyNTIwJTI1dTI2NjElMjUyMFVuaWNvZGUlMjUyMQ==
+b64_to_utf8('SSUyNTIwJTI1dTI2NjElMjUyMFVuaWNvZGUlMjUyMQ=='); // "I ♡ Unicode!"
+
+
+ +

Eine günstigere, zuverlässigere und effizientere Lösung ist, DOMString zunächst in eine UTF-8-kodierte Zeichenkette zu konvertieren, die sich für typed arrays eignet. Eine Anleitung bietet dieser Abschnitt.

+ +

Specifications

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

Browser compatibility

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Basic support{{CompatVersionUnknown}}{{CompatGeckoDesktop(1)}}[1]10{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureAndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{CompatVersionUnknown}}{{CompatGeckoMobile(1)}}{{CompatNo}}{{CompatUnknown}}{{CompatVersionUnknown}}
+
+ +

[1] btoa() is also available to XPCOM components implemented in JavaScript, even though window is not the global object in components.

+ +

See also

+ + diff --git a/files/de/web/api/settimeout/index.html b/files/de/web/api/settimeout/index.html new file mode 100644 index 0000000000..706f9a90b3 --- /dev/null +++ b/files/de/web/api/settimeout/index.html @@ -0,0 +1,330 @@ +--- +title: WindowTimers.setTimeout() +slug: Web/API/setTimeout +translation_of: Web/API/WindowOrWorkerGlobalScope/setTimeout +original_slug: Web/API/WindowOrWorkerGlobalScope/setTimeout +--- +
{{APIRef("HTML DOM")}}
+ +

Die Funktion setTimeout() der {{domxref("WindowOrWorkerGlobalScope")}}-Schnittstelle ruft nach der gegebenen Zeitspanne eine Funktion oder direkt angebenen Code auf.

+ +

Syntax

+ +
var timeoutID = window.setTimeout(funktion, zeitspanne, [parameter1, parameter2, ...]);
+var timeoutID = window.setTimeout(code, zeitspanne);
+
+ +

 

+ +

Parameter

+ +

 

+ +
+
funktion
+
Die {{jsxref("function", "Funktion")}}, die nach zeitspanne Millisekunden ausgeführt werden soll.
+
code
+
code in der alternativen Syntax ist eine Zeichenkette, die Code enthält, der nach zeitspanne Millisekunden ausgeführt werden soll.  code sollte aus den gleichen Gründen, die auch eval() zum Sicherheitsrisiko machen, nicht verwendet werden.
+
zeitspanne {{optional_inline}}
+
zeitspanne ist die Wartezeit in Millisekunden (ein Tausendstel einer Sekunde), nach der funktion bzw. code ausgeführt werden soll. Dieser Wert ist ein Mindestwert, die tatsächlich abgelaufene Zeit kann länger sein, siehe {{anch("Gründe für längere als gegebene Wartezeiten")}} weiter unten.
+
parameter1, ..., parameterN {{optional_inline}}
+
Diese Parameter werden an die funktion oder den code übergeben.
+
+ +
Anmerkung: Der Internet Explorer unterstützt bis einschließlich Version 9 die Übergabe von zusätzlichen Parametern nicht.
+ +

Rückgabewert

+ +

setTimeout() gibt eine ID zurück, die den eingerichteten Zeitgeber identifiziert; um die Wartezeit abzubrechen, kann sie an {{domxref("WindowOrWorkerGlobalScope.clearTimeout","clearTimeout()")}}  übergeben werden.

+ +

Jede ID wird von setTimeout() und setInterval() nur einmalig je Objekt (window oder Worker) verwendet.

+ +

Beispiel

+ +

HTML

+ +
<p>Beispiel</p>
+<button onclick="delayedAlert();">Zeige nach zwei Sekunden einen Alarm.</button>
+<p></p>
+<button onclick="clearAlert();">Alarm vorzeitig abbrechen.</button>
+ +

JavaScript

+ +
var timeoutID;
+
+function delayedAlert() {
+  timeoutID = window.setTimeout(slowAlert, 2000);
+}
+
+function slowAlert() {
+  alert('Das hat gedauert!');
+}
+
+function clearAlert() {
+  window.clearTimeout(timeoutID);
+}
+ +

Ergebnis

+ +

{{EmbedLiveSample('Example')}}

+ +

Siehe auch clearTimeout()

+ +

Polyfill

+ +

Der nachfolgende Polyfill-Code ermöglicht es, der aufzurufenden Funktion auch im Internet Explorer Parameter zu übergeben:

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

Eine andere Möglichkeit ist, die Funktion innerhalb einer anonymen Funktion aufzurufen:

+ +
setTimeout(function() {
+    funktion("eins", "zwei", "drei");
+}, 1000);
+
+ +

Ebenfalls kann die Funktion bind() genutzt werden:

+ +

 

+ +
setTimeout(function(arg1, arg2, arg3){}.bind(undefined, "eins", "zwei", "drei"), 1000);
+ +

 

+ +

Das "this"-Problem

+ +

In der an setTimeout() übergebenen Funktion wird this bei Aufruf einen falschen Wert enthalten. Dieses Problem wird detailliert in der JavaScript-Referenz beschrieben.

+ +

Erklärung

+ +

Von setTimeout() ausgeführter Code wird in einem anderen Kontext ausgeführt, als in dem setTimeout() aufgerufen wurde. this wird deshalb in der aufgerufenen Funktion window oder global entsprechen, nicht dem this des Bereichs, in dem  setTimeout() aufgerufen wurde. Beispiel:

+ +
myArray = ["null", "eins", "drei"];
+myArray.myMethod = function (sProperty) {
+    alert(arguments.length > 0 ? this[sProperty] : this);
+};
+
+myArray.myMethod(); // Ausgabe: "null,eins,zwei"
+myArray.myMethod(1); // Ausgabe: "eins"
+setTimeout(myArray.myMethod, 1000); // Ausgabe: "[object Window]" nach 1 Sekunde
+setTimeout(myArray.myMethod, 1500, "1"); // Ausgabe: "undefined" nach 1,5 Sekunden
+// Versuchen wir, 'this' zu übergeben
+setTimeout.call(myArray, myArray.myMethod, 2000); // Fehler: "NS_ERROR_XPC_BAD_OP_ON_WN_PROTO: Illegal operation on WrappedNative prototype object"
+setTimeout.call(myArray, myArray.myMethod, 2500, 2); // Der gleiche Fehler
+ +

Es gibt hier keine Möglichkeit, this an die aufzurufende Funktion durchzureichen.

+ +

Eine Lösungsmöglichkeit

+ +

Eine Möglichkeit, das Problem zu umgehen, ist es, die beiden eingebauten Funktionen setTimeout() und setInterval() durch zwei eigene zu ersetzen, die sich Function.prototype.call bedienen:

+ +
// 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);
+};
+ +
Hinweis: Diese beiden Ersatzfunktionen ermöglichen es auch, im Internet Explorer Parameter an die aufzurufende Funktion zu übergeben, wie es HTML5 vorsieht. Sie können daher auch als {{anch("Polyfill")}} benutzt werden.
+ +

Anmerkungen

+ +

Eine Wartezeit kann mit window.clearTimeout() abgebrochen werden.

+ +

Soll eine Funktion wiederholt alle n Millisekunden aufgerufen werden, ist window.setInterval() die bessere Wahl.

+ +

Passing string literals

+ +

Passing a string instead of a function to setTimeout() suffers from the same hazards as using eval.

+ +
// Correct
+window.setTimeout(function() {
+    alert("Hello World!");
+}, 500);
+
+// Incorrect
+window.setTimeout("alert(\"Hello World!\");", 500);
+
+
+ +

String literals are evaluated in the global context, so local symbols in the context where setTimeout() was called will not be available when the string is evaluated as code.

+ +

Gründe für längere als gegebene Wartezeiten

+ +

Aus verschiedenen Gründen kann die tatsächliche Zeit bis zum Aufruf der Funktion länger sein als mit setTimeout() angegeben wurde. Dieser Abschnitt beschreibt die beiden häufigsten.

+ +

Wartezeiten betragen 4ms oder mehr

+ +

Um das System nicht zu überlasten, begrenzen moderne Browser die Häufigkeit der von setTimeout() und setInterval() ausgelösten Ereignisse ab einer bestimmten Aufruftiefe oder -häufigkeit. Beispiel:

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

Chrome und Firefox drosseln nach dem fünften Aufruf, Safari nach dem sechsten, Edge bereits nach dem dritten.

+ +

Eine Wartezeit von 0 ms kann mit {{domxref("window.postMessage()")}} erreicht werden, wie hier beschrieben.

+ +

 

+ +
+

Hinweis: Die Mindestwartezeit, DOM_MIN_TIMEOUT_VALUE, beträgt 4 ms (Firefox-Einstellung dom.min_timeout_value), die Verschachtelungstiefe DOM_CLAMP_TIMEOUT_NESTING_LEVEL beträgt 5.

+
+ +
+

Hinweis: Der Wert 4 ms wurde mit HTML5 festgelegt und wird von allen Browsern umgesetzt, die nach 2010 erschienen sind. Vor {{geckoRelease("5.0")}} war der Mindestwert 10 ms.

+
+ +

 

+ +

 

+ +

Wartezeiten in inaktiven Tabs  größer als 1s

+ +

Um die Last noch weiter zu verringern, beträgt die Mindestwartezeit in sich im Hintergrund befindlichen Tabs grundsätzlich mindestens 1 s.

+ +

Firefox setzt diese Beschränkung seit Version 5 um (siehe {{bug(633421)}}). Der Wert von 1000 ms kann in der Einstellungen dom.min_background_timeout_value geändert werden.
+ Chrome setzt diese Beschränkung seit Version 11 um (crbug.com/66078).

+ +

Bei Firefox für Android beträgt seit Version 14 die Mindestwartezeit in sich im Hintergrund befindlichen Tabs 15 Minuten (siehe {{bug(736602)}}). Jegliche Aktivität in diesen Tabs kann auch vollständig angehalten werden.

+ +
+

Seit Version 50 gelten in Firefox keine Beschränkungen mehr, falls sich die Web Audio API {{domxref("AudioContext")}} im Wiedergabemodus befindet. Seit Firefox 51 gilt dies bereits für jegliche Dokumente mit einem {{domxref("AudioContext")}}, unabhängig von dessen Status.
+ Apps, die Musik Note für Note abspielen, konnten wegen der Beschränkungen den Takt nicht halten, sobald sie in den Hintergrund gelegt wurden.

+
+ +

Lastbedingte Verzögerungen

+ +

Zusätzlich zum aktiven Drosseln kann es zu verlängerten Wartezeiten kommen, falls das Dokument, der Browser oder das Betriebssystem anderweitig beschäftigt sind. Ein wichtiger Punkt in diesem Zusammenhang ist, dass die aufzurufende Funktion nicht ausgeführt werden kann, solange der Thread, der setTimeout() aufgerufen hat, noch aktiv ist:

+ +
function bla() {
+  console.log('bla wurde aufgerufen');
+}
+setTimeout(bla, 0);
+console.log('hinter setTimeout');
+ +

Ergebnis:

+ +
hinter setTimeout
+bla wurde aufgerufen
+ +

Obwohl setTimeout die sofortige Ausführung angewiesen wurde, wird der Aufruf von bla() in einer Warteschlange bis zur nächsten Gelegenheit zurückgestellt. Erst wenn der aktuell laufende Code ausgeführt wurde, werden die in der Warteschlange gesammelten Aufrufe abgearbeitet. In der Folge ist der Programmablauf nicht, wie eventuell erwartet.

+ +

Browserkompatibilität

+ +

{{ CompatibilityTable() }}

+ +
+ + + + + + + + + + + + + + + + + + + +
EigenschaftChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basis1.0{{ CompatGeckoDesktop("1") }}4.04.01.0
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
EigenschaftAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic1.01.0{{ CompatGeckoMobile("1") }}6.06.01.0
+
+ +

Spezifikation

+ +

Gehört zu DOM-Level 0, wie spezifiziert in HTML5.

+ +

Siehe auch

+ +
    +
  • {{domxref("window.setInterval")}}
  • +
  • {{domxref("window.requestAnimationFrame")}}
  • +
diff --git a/files/de/web/api/windoworworkerglobalscope/btoa/index.html b/files/de/web/api/windoworworkerglobalscope/btoa/index.html deleted file mode 100644 index 8d1d37cf9f..0000000000 --- a/files/de/web/api/windoworworkerglobalscope/btoa/index.html +++ /dev/null @@ -1,146 +0,0 @@ ---- -title: WindowBase64.btoa() -slug: Web/API/WindowOrWorkerGlobalScope/btoa -tags: - - API - - Méthode - - Referenz -translation_of: Web/API/WindowOrWorkerGlobalScope/btoa -original_slug: Web/API/WindowBase64/btoa ---- -
{{APIRef("HTML DOM")}}
- -

Erzeugt eine Base-64-kodierten ASCII-Zeichenkette aus einer "Zeichenkette" von Binärdaten.

- -

Hinweis: diese Funktion ist nicht für Raw-Unicode-Zeichenketten geeignet (siehe Abschnitt "Unicode-Zeichenketten" unten).

- -

Syntax

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

Example

- -
var encodedData = window.btoa("Hello, world"); // Zeichenkette kodieren
-var decodedData = window.atob(encodedData); // Zeichenkette dekodieren
-
- -

Hinweise

- -

Diese Methode kann verwendet werden, um Daten zu kodieren, übertragen, und mittels {{domxref("WindowBase64.atob","window.atob()")}} wieder zu dekodieren, welche andernfalls Übertragungsprobleme bereiten würden. Beispielsweise ist es möglich, die Steuerzeichen mit den ASCII-Werten 0 bis 31 zu kodieren.

- -

btoa() steht auch in JavaScript implementierten XPCOM-Komponenten zur Verfügung, auch wenn window in solchen Komponenten nicht das globale Objekt ist.

- -

Unicode-Zeichenketten

- -

In den meisten Browsern verursacht ein Aufruf von window.btoa() mit einer Unicode-Zeichenkette eine "Character Out Of Range"-Exception ("Zeichen außerhalb des zulässigen Wertebereichs").

- -

Das kann mithilfe eines solchen Code-Schemas vermieden werden (beigesteuert von Johan Sundström):

- -
function utf8_to_b64(str) {
-    return window.btoa(unescape(encodeURIComponent(str)));
-}
-
-function b64_to_utf8(str) {
-    return decodeURIComponent(escape(window.atob(str)));
-}
-
-// Usage:
-utf8_to_b64('✓ à la mode'); // JTI1dTI3MTMlMjUyMCUyNUUwJTI1MjBsYSUyNTIwbW9kZQ==
-b64_to_utf8('JTI1dTI3MTMlMjUyMCUyNUUwJTI1MjBsYSUyNTIwbW9kZQ=='); // "✓ à la mode"
-
-utf8_to_b64('I \u2661 Unicode!'); // SSUyNTIwJTI1dTI2NjElMjUyMFVuaWNvZGUlMjUyMQ==
-b64_to_utf8('SSUyNTIwJTI1dTI2NjElMjUyMFVuaWNvZGUlMjUyMQ=='); // "I ♡ Unicode!"
-
-
- -

Eine günstigere, zuverlässigere und effizientere Lösung ist, DOMString zunächst in eine UTF-8-kodierte Zeichenkette zu konvertieren, die sich für typed arrays eignet. Eine Anleitung bietet dieser Abschnitt.

- -

Specifications

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

Browser compatibility

- -
{{CompatibilityTable}}
- -
- - - - - - - - - - - - - - - - - - - -
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Basic support{{CompatVersionUnknown}}{{CompatGeckoDesktop(1)}}[1]10{{CompatVersionUnknown}}{{CompatVersionUnknown}}
-
- -
- - - - - - - - - - - - - - - - - - - -
FeatureAndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{CompatVersionUnknown}}{{CompatGeckoMobile(1)}}{{CompatNo}}{{CompatUnknown}}{{CompatVersionUnknown}}
-
- -

[1] btoa() is also available to XPCOM components implemented in JavaScript, even though window is not the global object in components.

- -

See also

- - diff --git a/files/de/web/api/windoworworkerglobalscope/settimeout/index.html b/files/de/web/api/windoworworkerglobalscope/settimeout/index.html deleted file mode 100644 index 3849d27e5b..0000000000 --- a/files/de/web/api/windoworworkerglobalscope/settimeout/index.html +++ /dev/null @@ -1,330 +0,0 @@ ---- -title: WindowTimers.setTimeout() -slug: Web/API/WindowOrWorkerGlobalScope/setTimeout -translation_of: Web/API/WindowOrWorkerGlobalScope/setTimeout -original_slug: Web/API/WindowTimers/setTimeout ---- -
{{APIRef("HTML DOM")}}
- -

Die Funktion setTimeout() der {{domxref("WindowOrWorkerGlobalScope")}}-Schnittstelle ruft nach der gegebenen Zeitspanne eine Funktion oder direkt angebenen Code auf.

- -

Syntax

- -
var timeoutID = window.setTimeout(funktion, zeitspanne, [parameter1, parameter2, ...]);
-var timeoutID = window.setTimeout(code, zeitspanne);
-
- -

 

- -

Parameter

- -

 

- -
-
funktion
-
Die {{jsxref("function", "Funktion")}}, die nach zeitspanne Millisekunden ausgeführt werden soll.
-
code
-
code in der alternativen Syntax ist eine Zeichenkette, die Code enthält, der nach zeitspanne Millisekunden ausgeführt werden soll.  code sollte aus den gleichen Gründen, die auch eval() zum Sicherheitsrisiko machen, nicht verwendet werden.
-
zeitspanne {{optional_inline}}
-
zeitspanne ist die Wartezeit in Millisekunden (ein Tausendstel einer Sekunde), nach der funktion bzw. code ausgeführt werden soll. Dieser Wert ist ein Mindestwert, die tatsächlich abgelaufene Zeit kann länger sein, siehe {{anch("Gründe für längere als gegebene Wartezeiten")}} weiter unten.
-
parameter1, ..., parameterN {{optional_inline}}
-
Diese Parameter werden an die funktion oder den code übergeben.
-
- -
Anmerkung: Der Internet Explorer unterstützt bis einschließlich Version 9 die Übergabe von zusätzlichen Parametern nicht.
- -

Rückgabewert

- -

setTimeout() gibt eine ID zurück, die den eingerichteten Zeitgeber identifiziert; um die Wartezeit abzubrechen, kann sie an {{domxref("WindowOrWorkerGlobalScope.clearTimeout","clearTimeout()")}}  übergeben werden.

- -

Jede ID wird von setTimeout() und setInterval() nur einmalig je Objekt (window oder Worker) verwendet.

- -

Beispiel

- -

HTML

- -
<p>Beispiel</p>
-<button onclick="delayedAlert();">Zeige nach zwei Sekunden einen Alarm.</button>
-<p></p>
-<button onclick="clearAlert();">Alarm vorzeitig abbrechen.</button>
- -

JavaScript

- -
var timeoutID;
-
-function delayedAlert() {
-  timeoutID = window.setTimeout(slowAlert, 2000);
-}
-
-function slowAlert() {
-  alert('Das hat gedauert!');
-}
-
-function clearAlert() {
-  window.clearTimeout(timeoutID);
-}
- -

Ergebnis

- -

{{EmbedLiveSample('Example')}}

- -

Siehe auch clearTimeout()

- -

Polyfill

- -

Der nachfolgende Polyfill-Code ermöglicht es, der aufzurufenden Funktion auch im Internet Explorer Parameter zu übergeben:

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

Eine andere Möglichkeit ist, die Funktion innerhalb einer anonymen Funktion aufzurufen:

- -
setTimeout(function() {
-    funktion("eins", "zwei", "drei");
-}, 1000);
-
- -

Ebenfalls kann die Funktion bind() genutzt werden:

- -

 

- -
setTimeout(function(arg1, arg2, arg3){}.bind(undefined, "eins", "zwei", "drei"), 1000);
- -

 

- -

Das "this"-Problem

- -

In der an setTimeout() übergebenen Funktion wird this bei Aufruf einen falschen Wert enthalten. Dieses Problem wird detailliert in der JavaScript-Referenz beschrieben.

- -

Erklärung

- -

Von setTimeout() ausgeführter Code wird in einem anderen Kontext ausgeführt, als in dem setTimeout() aufgerufen wurde. this wird deshalb in der aufgerufenen Funktion window oder global entsprechen, nicht dem this des Bereichs, in dem  setTimeout() aufgerufen wurde. Beispiel:

- -
myArray = ["null", "eins", "drei"];
-myArray.myMethod = function (sProperty) {
-    alert(arguments.length > 0 ? this[sProperty] : this);
-};
-
-myArray.myMethod(); // Ausgabe: "null,eins,zwei"
-myArray.myMethod(1); // Ausgabe: "eins"
-setTimeout(myArray.myMethod, 1000); // Ausgabe: "[object Window]" nach 1 Sekunde
-setTimeout(myArray.myMethod, 1500, "1"); // Ausgabe: "undefined" nach 1,5 Sekunden
-// Versuchen wir, 'this' zu übergeben
-setTimeout.call(myArray, myArray.myMethod, 2000); // Fehler: "NS_ERROR_XPC_BAD_OP_ON_WN_PROTO: Illegal operation on WrappedNative prototype object"
-setTimeout.call(myArray, myArray.myMethod, 2500, 2); // Der gleiche Fehler
- -

Es gibt hier keine Möglichkeit, this an die aufzurufende Funktion durchzureichen.

- -

Eine Lösungsmöglichkeit

- -

Eine Möglichkeit, das Problem zu umgehen, ist es, die beiden eingebauten Funktionen setTimeout() und setInterval() durch zwei eigene zu ersetzen, die sich Function.prototype.call bedienen:

- -
// 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);
-};
- -
Hinweis: Diese beiden Ersatzfunktionen ermöglichen es auch, im Internet Explorer Parameter an die aufzurufende Funktion zu übergeben, wie es HTML5 vorsieht. Sie können daher auch als {{anch("Polyfill")}} benutzt werden.
- -

Anmerkungen

- -

Eine Wartezeit kann mit window.clearTimeout() abgebrochen werden.

- -

Soll eine Funktion wiederholt alle n Millisekunden aufgerufen werden, ist window.setInterval() die bessere Wahl.

- -

Passing string literals

- -

Passing a string instead of a function to setTimeout() suffers from the same hazards as using eval.

- -
// Correct
-window.setTimeout(function() {
-    alert("Hello World!");
-}, 500);
-
-// Incorrect
-window.setTimeout("alert(\"Hello World!\");", 500);
-
-
- -

String literals are evaluated in the global context, so local symbols in the context where setTimeout() was called will not be available when the string is evaluated as code.

- -

Gründe für längere als gegebene Wartezeiten

- -

Aus verschiedenen Gründen kann die tatsächliche Zeit bis zum Aufruf der Funktion länger sein als mit setTimeout() angegeben wurde. Dieser Abschnitt beschreibt die beiden häufigsten.

- -

Wartezeiten betragen 4ms oder mehr

- -

Um das System nicht zu überlasten, begrenzen moderne Browser die Häufigkeit der von setTimeout() und setInterval() ausgelösten Ereignisse ab einer bestimmten Aufruftiefe oder -häufigkeit. Beispiel:

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

Chrome und Firefox drosseln nach dem fünften Aufruf, Safari nach dem sechsten, Edge bereits nach dem dritten.

- -

Eine Wartezeit von 0 ms kann mit {{domxref("window.postMessage()")}} erreicht werden, wie hier beschrieben.

- -

 

- -
-

Hinweis: Die Mindestwartezeit, DOM_MIN_TIMEOUT_VALUE, beträgt 4 ms (Firefox-Einstellung dom.min_timeout_value), die Verschachtelungstiefe DOM_CLAMP_TIMEOUT_NESTING_LEVEL beträgt 5.

-
- -
-

Hinweis: Der Wert 4 ms wurde mit HTML5 festgelegt und wird von allen Browsern umgesetzt, die nach 2010 erschienen sind. Vor {{geckoRelease("5.0")}} war der Mindestwert 10 ms.

-
- -

 

- -

 

- -

Wartezeiten in inaktiven Tabs  größer als 1s

- -

Um die Last noch weiter zu verringern, beträgt die Mindestwartezeit in sich im Hintergrund befindlichen Tabs grundsätzlich mindestens 1 s.

- -

Firefox setzt diese Beschränkung seit Version 5 um (siehe {{bug(633421)}}). Der Wert von 1000 ms kann in der Einstellungen dom.min_background_timeout_value geändert werden.
- Chrome setzt diese Beschränkung seit Version 11 um (crbug.com/66078).

- -

Bei Firefox für Android beträgt seit Version 14 die Mindestwartezeit in sich im Hintergrund befindlichen Tabs 15 Minuten (siehe {{bug(736602)}}). Jegliche Aktivität in diesen Tabs kann auch vollständig angehalten werden.

- -
-

Seit Version 50 gelten in Firefox keine Beschränkungen mehr, falls sich die Web Audio API {{domxref("AudioContext")}} im Wiedergabemodus befindet. Seit Firefox 51 gilt dies bereits für jegliche Dokumente mit einem {{domxref("AudioContext")}}, unabhängig von dessen Status.
- Apps, die Musik Note für Note abspielen, konnten wegen der Beschränkungen den Takt nicht halten, sobald sie in den Hintergrund gelegt wurden.

-
- -

Lastbedingte Verzögerungen

- -

Zusätzlich zum aktiven Drosseln kann es zu verlängerten Wartezeiten kommen, falls das Dokument, der Browser oder das Betriebssystem anderweitig beschäftigt sind. Ein wichtiger Punkt in diesem Zusammenhang ist, dass die aufzurufende Funktion nicht ausgeführt werden kann, solange der Thread, der setTimeout() aufgerufen hat, noch aktiv ist:

- -
function bla() {
-  console.log('bla wurde aufgerufen');
-}
-setTimeout(bla, 0);
-console.log('hinter setTimeout');
- -

Ergebnis:

- -
hinter setTimeout
-bla wurde aufgerufen
- -

Obwohl setTimeout die sofortige Ausführung angewiesen wurde, wird der Aufruf von bla() in einer Warteschlange bis zur nächsten Gelegenheit zurückgestellt. Erst wenn der aktuell laufende Code ausgeführt wurde, werden die in der Warteschlange gesammelten Aufrufe abgearbeitet. In der Folge ist der Programmablauf nicht, wie eventuell erwartet.

- -

Browserkompatibilität

- -

{{ CompatibilityTable() }}

- -
- - - - - - - - - - - - - - - - - - - -
EigenschaftChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basis1.0{{ CompatGeckoDesktop("1") }}4.04.01.0
-
- -
- - - - - - - - - - - - - - - - - - - - - -
EigenschaftAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic1.01.0{{ CompatGeckoMobile("1") }}6.06.01.0
-
- -

Spezifikation

- -

Gehört zu DOM-Level 0, wie spezifiziert in HTML5.

- -

Siehe auch

- -
    -
  • {{domxref("window.setInterval")}}
  • -
  • {{domxref("window.requestAnimationFrame")}}
  • -
diff --git a/files/es/_redirects.txt b/files/es/_redirects.txt index 422cc4e36c..393d653e5f 100644 --- a/files/es/_redirects.txt +++ b/files/es/_redirects.txt @@ -1573,17 +1573,27 @@ /es/docs/Web/API/WebSockets_API/Escribiendo_servidor_WebSocket /es/docs/Web/API/WebSockets_API/Writing_WebSocket_server /es/docs/Web/API/WebSockets_API/Escribiendo_servidores_con_WebSocket /es/docs/Web/API/WebSockets_API/Writing_WebSocket_servers /es/docs/Web/API/Web_Speech_API/Uso_de_la_Web_Speech_API /es/docs/Web/API/Web_Speech_API/Using_the_Web_Speech_API -/es/docs/Web/API/Window.clearTimeout /es/docs/Web/API/WindowOrWorkerGlobalScope/clearTimeout +/es/docs/Web/API/Window.clearTimeout /es/docs/Web/API/clearTimeout /es/docs/Web/API/Window.navigator /es/docs/Web/API/Window/navigator /es/docs/Web/API/Window.onbeforeunload /es/docs/Web/API/WindowEventHandlers/onbeforeunload -/es/docs/Web/API/Window.setTimeout /es/docs/Web/API/WindowOrWorkerGlobalScope/setTimeout -/es/docs/Web/API/WindowBase64.atob /es/docs/Web/API/WindowOrWorkerGlobalScope/atob +/es/docs/Web/API/Window.setTimeout /es/docs/Web/API/setTimeout +/es/docs/Web/API/WindowBase64.atob /es/docs/Web/API/atob /es/docs/Web/API/WindowBase64/Base64_codificando_y_decodificando /es/docs/Glossary/Base64 -/es/docs/Web/API/WindowBase64/atob /es/docs/Web/API/WindowOrWorkerGlobalScope/atob -/es/docs/Web/API/WindowTimers/clearInterval /es/docs/Web/API/WindowOrWorkerGlobalScope/clearInterval -/es/docs/Web/API/WindowTimers/clearTimeout /es/docs/Web/API/WindowOrWorkerGlobalScope/clearTimeout -/es/docs/Web/API/WindowTimers/setInterval /es/docs/Web/API/WindowOrWorkerGlobalScope/setInterval -/es/docs/Web/API/WindowTimers/setTimeout /es/docs/Web/API/WindowOrWorkerGlobalScope/setTimeout +/es/docs/Web/API/WindowBase64/atob /es/docs/Web/API/atob +/es/docs/Web/API/WindowOrWorkerGlobalScope/atob /es/docs/Web/API/atob +/es/docs/Web/API/WindowOrWorkerGlobalScope/caches /es/docs/Web/API/caches +/es/docs/Web/API/WindowOrWorkerGlobalScope/clearInterval /es/docs/Web/API/clearInterval +/es/docs/Web/API/WindowOrWorkerGlobalScope/clearTimeout /es/docs/Web/API/clearTimeout +/es/docs/Web/API/WindowOrWorkerGlobalScope/createImageBitmap /es/docs/Web/API/createImageBitmap +/es/docs/Web/API/WindowOrWorkerGlobalScope/fetch /es/docs/Web/API/fetch +/es/docs/Web/API/WindowOrWorkerGlobalScope/indexedDB /es/docs/Web/API/indexedDB +/es/docs/Web/API/WindowOrWorkerGlobalScope/isSecureContext /es/docs/Web/API/isSecureContext +/es/docs/Web/API/WindowOrWorkerGlobalScope/setInterval /es/docs/Web/API/setInterval +/es/docs/Web/API/WindowOrWorkerGlobalScope/setTimeout /es/docs/Web/API/setTimeout +/es/docs/Web/API/WindowTimers/clearInterval /es/docs/Web/API/clearInterval +/es/docs/Web/API/WindowTimers/clearTimeout /es/docs/Web/API/clearTimeout +/es/docs/Web/API/WindowTimers/setInterval /es/docs/Web/API/setInterval +/es/docs/Web/API/WindowTimers/setTimeout /es/docs/Web/API/setTimeout /es/docs/Web/API/XMLHttpRequest/FormData /es/docs/Web/API/FormData /es/docs/Web/API/event.defaultPrevented /es/docs/Web/API/Event/defaultPrevented /es/docs/Web/API/event.which /es/docs/Web/API/KeyboardEvent/which diff --git a/files/es/_wikihistory.json b/files/es/_wikihistory.json index 535a52b77e..3808f684eb 100644 --- a/files/es/_wikihistory.json +++ b/files/es/_wikihistory.json @@ -9120,79 +9120,6 @@ "chrisdavidmills" ] }, - "Web/API/WindowOrWorkerGlobalScope/atob": { - "modified": "2019-03-23T23:03:12.715Z", - "contributors": [ - "fscholz", - "sathyasanles" - ] - }, - "Web/API/WindowOrWorkerGlobalScope/caches": { - "modified": "2019-03-23T22:16:45.016Z", - "contributors": [ - "ivannieto" - ] - }, - "Web/API/WindowOrWorkerGlobalScope/clearInterval": { - "modified": "2019-03-23T22:56:16.485Z", - "contributors": [ - "Guitxo" - ] - }, - "Web/API/WindowOrWorkerGlobalScope/clearTimeout": { - "modified": "2019-06-18T10:20:27.972Z", - "contributors": [ - "AlePerez92", - "fscholz", - "basemnassar11", - "VictorArias" - ] - }, - "Web/API/WindowOrWorkerGlobalScope/createImageBitmap": { - "modified": "2020-10-15T22:14:17.553Z", - "contributors": [ - "Bumxu" - ] - }, - "Web/API/WindowOrWorkerGlobalScope/fetch": { - "modified": "2020-10-15T22:01:57.457Z", - "contributors": [ - "fscholz", - "jagomf" - ] - }, - "Web/API/WindowOrWorkerGlobalScope/indexedDB": { - "modified": "2019-03-23T22:16:36.537Z", - "contributors": [ - "ivannieto" - ] - }, - "Web/API/WindowOrWorkerGlobalScope/isSecureContext": { - "modified": "2019-03-23T22:16:45.834Z", - "contributors": [ - "ivannieto" - ] - }, - "Web/API/WindowOrWorkerGlobalScope/setInterval": { - "modified": "2020-08-24T18:02:23.092Z", - "contributors": [ - "mastertrooper", - "Makinita", - "Klius", - "claudionebbia" - ] - }, - "Web/API/WindowOrWorkerGlobalScope/setTimeout": { - "modified": "2019-03-23T23:17:29.378Z", - "contributors": [ - "BubuAnabelas", - "vltamara", - "nauj27", - "fscholz", - "AshfaqHossain", - "VictorArias" - ] - }, "Web/API/Worker": { "modified": "2019-03-23T22:48:01.797Z", "contributors": [ @@ -9277,6 +9204,34 @@ "mmednik" ] }, + "Web/API/atob": { + "modified": "2019-03-23T23:03:12.715Z", + "contributors": [ + "fscholz", + "sathyasanles" + ] + }, + "Web/API/caches": { + "modified": "2019-03-23T22:16:45.016Z", + "contributors": [ + "ivannieto" + ] + }, + "Web/API/clearInterval": { + "modified": "2019-03-23T22:56:16.485Z", + "contributors": [ + "Guitxo" + ] + }, + "Web/API/clearTimeout": { + "modified": "2019-06-18T10:20:27.972Z", + "contributors": [ + "AlePerez92", + "fscholz", + "basemnassar11", + "VictorArias" + ] + }, "Web/API/console/assert": { "modified": "2019-03-23T22:47:53.587Z", "contributors": [ @@ -9285,6 +9240,31 @@ "danycoro" ] }, + "Web/API/createImageBitmap": { + "modified": "2020-10-15T22:14:17.553Z", + "contributors": [ + "Bumxu" + ] + }, + "Web/API/fetch": { + "modified": "2020-10-15T22:01:57.457Z", + "contributors": [ + "fscholz", + "jagomf" + ] + }, + "Web/API/indexedDB": { + "modified": "2019-03-23T22:16:36.537Z", + "contributors": [ + "ivannieto" + ] + }, + "Web/API/isSecureContext": { + "modified": "2019-03-23T22:16:45.834Z", + "contributors": [ + "ivannieto" + ] + }, "Web/API/notification": { "modified": "2019-06-28T05:54:12.854Z", "contributors": [ @@ -9338,6 +9318,26 @@ "Davdriver" ] }, + "Web/API/setInterval": { + "modified": "2020-08-24T18:02:23.092Z", + "contributors": [ + "mastertrooper", + "Makinita", + "Klius", + "claudionebbia" + ] + }, + "Web/API/setTimeout": { + "modified": "2019-03-23T23:17:29.378Z", + "contributors": [ + "BubuAnabelas", + "vltamara", + "nauj27", + "fscholz", + "AshfaqHossain", + "VictorArias" + ] + }, "Web/Accessibility": { "modified": "2020-09-22T14:24:03.363Z", "contributors": [ diff --git a/files/es/web/api/atob/index.html b/files/es/web/api/atob/index.html new file mode 100644 index 0000000000..71044fc0ab --- /dev/null +++ b/files/es/web/api/atob/index.html @@ -0,0 +1,112 @@ +--- +title: WindowBase64.atob() +slug: Web/API/atob +translation_of: Web/API/WindowOrWorkerGlobalScope/atob +original_slug: Web/API/WindowOrWorkerGlobalScope/atob +--- +

{{APIRef}}

+ +

La función WindowBase64.atob() descodifica una cadena de datos que ha sido codificada utilizando la codificación en base-64. Puedes utilizar el método {{domxref("window.btoa()")}} para codificar y transmitir datos que, de otro modo podrían generar problemas de comunicación. Luego de ser transmitidos se puede usar el método window.atob() para decodificar los datos de nuevo. Por ejemplo, puedes codificar, transmitir y decodificar los caracteres de control como valores ASCII 0 a 31.

+ +

For use with Unicode or UTF-8 strings, see this note at Base64 encoding and decoding and this note at window.btoa().

+ +

Syntax

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

Example

+ +
var encodedData = window.btoa("Hello, world"); // encode a string
+var decodedData = window.atob(encodedData); // decode the string
+ +

Specifications

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

Browser compatibility

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Basic support{{CompatVersionUnknown}}{{CompatGeckoDesktop(1)}}[1][2]10{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureAndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{CompatVersionUnknown}}{{CompatGeckoMobile(1)}}{{CompatNo}}{{CompatUnknown}}{{CompatVersionUnknown}}
+
+ +

[1]  atob() is also available to XPCOM components implemented in JavaScript, even though window is not the global object in components.

+ +

[2] Starting with Firefox 27, this atob() method ignores all space characters in the argument to comply with the latest HTML5 spec. ({{ bug(711180) }})

+ +

See also

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

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

+ +

La propiedad de sólo-lectura caches, de la interfaz {{domxref("WindowOrWorkerGlobalScope")}}, devuelve el objeto {{domxref("CacheStorage")}} asociado al contexto actual. Este objeto habilita funcionalidades como guardar assets para su utilización offline, y generar respuestas personalizadas a las peticiones.

+ +

Sintaxis

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

Valor

+ +

Un objeto {{domxref("CacheStorage")}}.

+ +

Ejemplo

+ +

El siguiente ejemplo muestra la forma en la que utilizarías una cache en un contexto de service worker para guardar assets offline.

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

Especificaciones

+ + + + + + + + + + + + + + + + + + + +
EspecificaciónEstadoComentario
{{SpecName('Service Workers', '#self-caches', 'caches')}}{{Spec2('Service Workers')}}Definido en un WindowOrWorkerGlobalScope parcial en la última especificación.
{{SpecName('Service Workers')}}{{Spec2('Service Workers')}}Definición inicial.
+ +

Compatibilidad de Navegadores

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + +
CaracterísticaChromeFirefox (Gecko)Internet ExplorerOperaSafari
Soporte Básico40.0{{CompatGeckoDesktop(42)}}
+ {{CompatGeckoDesktop(52)}}[1]
{{CompatNo}}{{CompatUnknown}}{{CompatNo}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
CaracterísticaAndroidChrome para AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Soporte Básico{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatGeckoMobile(42)}}
+ {{CompatGeckoMobile(52)}}[1]
{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +

[1] las caches se definen ahora en el mixin {{domxref("WindowOrWorkerGlobalScope")}}.

+ +

Ver también

+ + diff --git a/files/es/web/api/clearinterval/index.html b/files/es/web/api/clearinterval/index.html new file mode 100644 index 0000000000..df9ac60205 --- /dev/null +++ b/files/es/web/api/clearinterval/index.html @@ -0,0 +1,44 @@ +--- +title: WindowTimers.clearInterval() +slug: Web/API/clearInterval +translation_of: Web/API/WindowOrWorkerGlobalScope/clearInterval +original_slug: Web/API/WindowOrWorkerGlobalScope/clearInterval +--- +
+
{{APIRef("HTML DOM")}}
+
+ +

Cancela una acción reiterativa que se inició mediante una llamada a {{domxref("window.setInterval", "setInterval")}}.

+ +

Sintaxis

+ +
window.clearInterval(intervalID)
+
+ +

intervalID es el identificador de la acción reiterativa que se desea cancelar. Este ID se obtiene a partir de setInterval().

+ +

Ejemplo

+ +

Vea el ejemplo de setInterval().

+ +

Especificación

+ + + + + + + + +
{{SpecName('HTML WHATWG', 'timers.html#timers', 'clearInterval')}}{{Spec2('HTML WHATWG')}}
+ +

Vea también

+ +
    +
  • JavaScript timers
  • +
  • {{domxref("WindowTimers.setTimeout")}}
  • +
  • {{domxref("WindowTimers.setInterval")}}
  • +
  • {{domxref("WindowTimers.clearTimeout")}}
  • +
  • {{domxref("window.requestAnimationFrame")}}
  • +
  • Daemons management
  • +
diff --git a/files/es/web/api/cleartimeout/index.html b/files/es/web/api/cleartimeout/index.html new file mode 100644 index 0000000000..d86391e675 --- /dev/null +++ b/files/es/web/api/cleartimeout/index.html @@ -0,0 +1,64 @@ +--- +title: window.clearTimeout +slug: Web/API/clearTimeout +translation_of: Web/API/WindowOrWorkerGlobalScope/clearTimeout +original_slug: Web/API/WindowOrWorkerGlobalScope/clearTimeout +--- +
{{ApiRef}}
+ +

Resumen

+ +

Borra el retraso asignado por {{domxref("window.setTimeout","window.setTimeout()")}}.

+ +

Sintaxis

+ +
window.clearTimeout(timeoutID)
+
+ +
    +
  • timeoutID es el ID del timeout que desee borrar, retornado por {{domxref("window.setTimeout","window.setTimeout()")}}.
  • +
+ +

Ejemplo

+ +

Ejecute el script de abajo en el contexto de una página web y haga clic en la página una vez. Verá un mensaje emergente en un segundo. Si permanece haciendo clic en la página cada segundo, la alerta nunca aparece.

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

Notas

+ +

Pasar un ID inválido a clearTimeout no tiene ningún efecto (y no lanza una excepción).

+ +

Especificación

+ +

DOM Nivel 0. Especificado en HTML5.

+ +

Vea también

+ +
    +
  • JavaScript timers
  • +
  • {{domxref("window.setTimeout")}}
  • +
  • {{domxref("window.setInterval")}}
  • +
  • {{domxref("window.clearInterval")}}
  • +
  • {{domxref("window.requestAnimationFrame")}}
  • +
  • Daemons management
  • +
diff --git a/files/es/web/api/createimagebitmap/index.html b/files/es/web/api/createimagebitmap/index.html new file mode 100644 index 0000000000..4f6c6fabe4 --- /dev/null +++ b/files/es/web/api/createimagebitmap/index.html @@ -0,0 +1,109 @@ +--- +title: self.createImageBitmap() +slug: Web/API/createImageBitmap +tags: + - API + - Canvas + - DOM + - Referencia + - WindowOrWorkerGlobalScope + - createImageBitmap + - metodo +translation_of: Web/API/WindowOrWorkerGlobalScope/createImageBitmap +original_slug: Web/API/WindowOrWorkerGlobalScope/createImageBitmap +--- +
{{APIRef("Canvas API")}}
+ +

El método createImageBitmap() crea un bitmap a partir de un recurso especificado, opcionalmente recortado para mostrar únicamente una porción de este. El método existe a nivel global como parte, tanto de las ventanas (window), como de los workers. Este admite una variedad de tipos de entrada, y devuelve una {{domxref("Promise")}} que es resuelta con un {{domxref("ImageBitmap")}}.

+ +

Sintaxis

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

Parámetros

+ +
+
image
+
Un recurso/imagen origen, que puede uno de los siguientes elementos: {{HTMLElement("img")}}, SVG {{SVGElement("image")}}, {{HTMLElement("video")}}, {{HTMLElement("canvas")}}, {{domxref("HTMLImageElement")}}, {{domxref("SVGImageElement")}}, {{domxref("HTMLVideoElement")}}, {{domxref("HTMLCanvasElement")}}, {{domxref("Blob")}}, {{domxref("ImageData")}}, {{domxref("ImageBitmap")}}, o {{domxref("OffscreenCanvas")}}.
+
sx
+
La coordenada x del rectángulo que será usado para la extracción del ImageBitmap.
+
sy
+
La coordenada y del rectángulo que será usado para la extracción del ImageBitmap.
+
sw
+
La anchura del rectángulo que será usado para extraer el ImageBitmap. El valor podría ser negativo.
+
sh
+
La altura del rectángulo que será usado para extraer el ImageBitmap. El valor podría ser negativo.
+
options {{optional_inline}}
+
Un objeto que proporciona opciones para la extracción de la imagen. Las opciones posibles son: +
    +
  • imageOrientation: Especifica si la imagen debe ser extraida tal y como se muestra, o debe ser volteada verticalmente. Las valores posibles: none (por defecto) o flipY.
  • +
  • premultiplyAlpha: Especifica si los canales de color del mapa de bits generado deben premultiplicarse por el canal alpha. Uno de: none, premultiply, o default (por defecto).
  • +
  • colorSpaceConversion: Especifica si la imagen debe ser decodificada usando conversión del espacio de color. Uno de: none o default (por defecto). El valor default indica que se usará la implementación que haya disponible.
  • +
  • resizeWidth: Un entero largo que especifica la anchura final.
  • +
  • resizeHeight: Un entero largo que especifica la altura final.
  • +
  • resizeQuality: Especifica que algorítmo debe ser usado en el redimensionado para alcanzar las dimensiones deseadas. Uno de estos valores: pixelated, low (por defecto), medium, o high.
  • +
+
+
+ +

Valor devuelto

+ +

Una {{domxref("Promise")}} que es resuelta con un objeto {{domxref("ImageBitmap")}}, el cual contiene los datos del mapa de bits generado para el rectángulo dado.

+ +

Ejemplo

+ +

Creando sprites desde un sprite sheet

+ +

El siguiente ejemplo carga un sprite sheet, extrae los sprites, y muestra cada uno de ellos en el canvas. Un sprite sheet es una imagen que contiene multiples imágenes más pequeñas, que finalmente son utilizadas de manera individual.

+ +
var canvas = document.getElementById('myCanvas'),
+ctx = canvas.getContext('2d'),
+image = new Image();
+
+// Esperar que el sprite sheet se cargue
+image.onload = function() {
+  Promise.all([
+    // Recortar dos sprites del conjunto
+    createImageBitmap(image, 0, 0, 32, 32),
+    createImageBitmap(image, 32, 0, 32, 32)
+  ]).then(function(sprites) {
+    // Pintar cada uno de los sprites en el canvas
+    ctx.drawImage(sprites[0], 0, 0);
+    ctx.drawImage(sprites[1], 32, 32);
+  });
+}
+
+// Cargar el sprite sheet desde un archivo de imagen
+image.src = 'sprites.png';
+
+ +

Especificaciones

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

Compatibilidad con navegadores

+ + + +

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

+ +

Ver también

+ +
    +
  • {{domxref("CanvasRenderingContext2D.drawImage()")}}
  • +
  • {{domxref("ImageData")}}
  • +
diff --git a/files/es/web/api/fetch/index.html b/files/es/web/api/fetch/index.html new file mode 100644 index 0000000000..0b2f38916a --- /dev/null +++ b/files/es/web/api/fetch/index.html @@ -0,0 +1,178 @@ +--- +title: WindowOrWorkerGlobalScope.fetch() +slug: Web/API/fetch +tags: + - API + - Experimental + - Fetch + - Fetch API + - GlobalFetch + - Petición + - Referencia + - metodo + - solicitud +translation_of: Web/API/WindowOrWorkerGlobalScope/fetch +original_slug: Web/API/WindowOrWorkerGlobalScope/fetch +--- +
{{APIRef("Fetch API")}}
+ +

El método fetch() del mixin {{domxref("WindowOrWorkerGlobalScope")}} lanza el proceso de solicitud de un recurso de la red. Esto devuelve una promesa que resuelve al objeto {{domxref("Response")}} que representa la respuesta a la solicitud realizada.

+ +

Tanto {{domxref("Window")}} como {{domxref("WorkerGlobalScope")}} implementan WorkerOrGlobalScope, por lo que el método fetch() está disponible en prácticamente cualquier contexto desde el que se pueda necesitar solicitar un recurso.

+ +

Una promesa {{domxref("WindowOrWorkerGlobalScope.fetch","fetch()")}} se rechaza con un {{jsxref("TypeError")}} cuando sucede un error en la red, aunque normalmente significa un tema de permisos o similar. Una comprobación más precisa de una solicitud con fetch() debería comprobar que la promesa se resuelve, y que la propiedad {{domxref("Response.ok")}} tiene valor true. Un estatus HTTP 404 no constituye un error de red.

+ +

El método fetch() es controlado por la directiva connect-src de la Política de Seguridad de Contenido (Content Security Policy) en lugar de la directiva del recurso que se solicita.

+ +
+

Nota: Los parámetros del método fetch() son indénticos a los del constructor de {{domxref("Request.Request","Request()")}}.

+
+ +

Sintaxis

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

Parámetros

+ +
+
input
+
Define el recurso que se quiere solicitar. Puede ser: +
    +
  • Un {{domxref("USVString")}} con la URL del recurso a solicitar. Algunos navegadores aceptan los esquemas blob: y data:.
  • +
  • Un objeto {{domxref("Request")}}.
  • +
+
+
init {{optional_inline}}
+
Objeto de opciones que contiene configuraciones para personalizar la solicitud. Estas opciones pueden ser: +
    +
  • method: El método de solicitud, p.ej., GET, POST.
  • +
  • headers: Cualquier cabecera que se quiera añadir a la solicitud, contenidas en un objeto {{domxref("Headers")}} o un objeto literal con valores {{domxref("ByteString")}}.
  • +
  • body: Cualquier cuerpo que se quiera añadir a la solicitud: puede ser un {{domxref("Blob")}}, {{domxref("BufferSource")}}, {{domxref("FormData")}}, {{domxref("URLSearchParams")}}, u objeto {{domxref("USVString")}}. Nótese que las solicitudes con métodos GETHEAD no pueden tener cuerpo.
  • +
  • mode: El modo a usar en la solicitud, p.ej., cors, no-cors, o same-origin.
  • +
  • credentials: Las credenciales que se quieran utilizar para la solicitud: omit, same-origin, o include. Para enviar automáticamente las cookies del dominio actual, debe indicarse esta opción. Desde Chrome 50, esta propiedad también acepta una instancia de {{domxref("FederatedCredential")}} o de {{domxref("PasswordCredential")}}.
  • +
  • cache: El modo de caché a utilizar en la solicitud: default, no-store, reload, no-cache, force-cache, o only-if-cached.
  • +
  • redirect: El modo de redirección a usar: follow (seguir redirecciones automáticamente), error (abortar si sucede un error durante la redirección), o manual (gestionar redirecciones manualmente). El valor por defecto en Chrome es follow (hasta la versión 46 era manual).
  • +
  • referrer: Un {{domxref("USVString")}} que especifique no-referrerclient, o una URL. El valor por defecto es client.
  • +
  • referrerPolicy: Especifica el valor de la cabecera HTTP referer. Puede ser no-referrer, no-referrer-when-downgrade, origin, origin-when-cross-origin, unsafe-url.
  • +
  • integrity: Contiene el valor de integridad de subrecurso (subresource integrity) de la solicitud (p.ej., sha256-BpfBw7ivV8q2jLiT13fxDYAe2tJllusRSZ273h2nFSE=).
  • +
  • keepalive: La opción keepalive se puede usar para permitir que recurso dure más que la página. Las solicitudes con el indicador keepalive son un reemplazo de la API {{domxref("Navigator.sendBeacon()")}}. 
  • +
  • signal: Una instancia de objeto {{domxref("AbortSignal")}}; permite comunicarse con con una solicitud vigente y abortarla si se desea via {{domxref("AbortController")}}.
  • +
+
+
+ +

Return value

+ +

Una {{domxref("Promise")}} que resuelve a un objeto {{domxref("Response")}}.

+ +

Excepciones

+ + + + + + + + + + + + + + + + + + +
TipoDescriptción
AbortErrorSe abortó la solicitud (mediante {{domxref("AbortController.abort()")}}).
TypeErrorDesde Firefox 43, fetch() lanza un TypeError si la URL tiene credenciales, como en http://usuario:clave@ejemplo.com.
+ +

Ejemplo

+ +

En el ejemplo de solicitud con Request (ver Fetch Request live) creamos un nuevo objeto {{domxref("Request")}} usando el constructor pertinente, y realizamos una solicitud usando fetch(). Dado que estamos solicitando una imagen, ejecutamos {{domxref("Body.blob()")}} en la respuesta para darle el tipo MIME correspondiente para que sea gestionada apropiadamente, luego creamos un objeto URL de ella para mostrarla en un elemento {{htmlelement("img")}}.

+ +
var miImagen = document.querySelector('img');
+
+var miSolicitud = new Request('flores.jpg');
+
+fetch(miSolicitud).then(function(respuesta) {
+  return respuesta.blob();
+}).then(function(respuesta) {
+  var objeto = URL.createObjectURL(respuesta);
+  miImagen.src = objeto;
+});
+ +

En el ejemplo de solicitud con inicializador y Request (ver Fetch Request init live) hacemos lo mismo pero además pasamos un objeto inicializador cuando invocamos el fetch():

+ +
var miImagen = document.querySelector('img');
+
+var misCabeceras = new Headers();
+misCabeceras.append('Content-Type', 'image/jpeg');
+
+var miInicializador = { method: 'GET',
+                        headers: misCabeceras,
+                        mode: 'cors',
+                        cache: 'default' };
+
+var miSolicitud = new Request('flores.jpg');
+
+fetch(miSolicitud,miInicializador).then(function(respuesta) {
+  ...
+});
+ +

Nótese que también podríamos pasar el objeto inicializador con el constructor de Request para conseguir el mismo efecto, p.ej.:

+ +
var miSolicitud = new Request('flores.jpg', miInicializador);
+ +

También se puede usar un objeto literal a modo de headers en init.

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

Especificaciones

+ + + + + + + + + + + + + + + + + + + + + + + + +
EspecificaciónEstadoComentarios
{{SpecName('Fetch','#fetch-method','fetch()')}}{{Spec2('Fetch')}}Definida parcialmente en WindowOrWorkerGlobalScope en la especificación más reciente.
{{SpecName('Fetch','#dom-global-fetch','fetch()')}}{{Spec2('Fetch')}}Definición inicial
{{SpecName('Credential Management')}}{{Spec2('Credential Management')}}Añade una instancia de {{domxref("FederatedCredential")}} o {{domxref("PasswordCredential")}} como valor posible para init.credentials.
+ +

Compatibilidad con navegadores

+ + + +

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

+ +

Ver también

+ + diff --git a/files/es/web/api/indexeddb/index.html b/files/es/web/api/indexeddb/index.html new file mode 100644 index 0000000000..6fa82a2310 --- /dev/null +++ b/files/es/web/api/indexeddb/index.html @@ -0,0 +1,142 @@ +--- +title: WindowOrWorkerGlobalScope.indexedDB +slug: Web/API/indexedDB +translation_of: Web/API/WindowOrWorkerGlobalScope/indexedDB +original_slug: Web/API/WindowOrWorkerGlobalScope/indexedDB +--- +

{{ APIRef() }}

+ +

La propiedad indexedDB del mixin {{domxref("WindowOrWorkerGlobalScope")}} proporciona un mecanismo para que las aplicaciones puedan acceder asíncronamente a las capacidades de las bases de datos indexadas.

+ +

Sintaxis

+ +
var DBOpenRequest = self.indexedDB.open('toDoList');
+ +

Valor

+ +

Un objeto {{domxref("IDBFactory")}}.

+ +

Ejemplo

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

Especificaciones

+ + + + + + + + + + + + + + + + + + + +
EspecificaciónEstadoComentario
{{SpecName('IndexedDB 2', '#dom-windoworworkerglobalscope-indexeddb', 'indexedDB')}}{{Spec2('IndexedDB 2')}}Definido en un WindowOrWorkerGlobalScope parcial en la última especificación.
{{SpecName('IndexedDB', '#widl-IDBEnvironment-indexedDB', 'indexedDB')}}{{Spec2('IndexedDB')}}Definición inicial.
+ +

Compatibilidad de Navegadores

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
CaracterísticaChromeEdgeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Soporte básico23{{property_prefix("webkit")}}
+ 24
{{CompatVersionUnknown}}10 {{property_prefix("moz")}}
+ {{CompatGeckoDesktop("16.0")}}
+ {{CompatGeckoDesktop("52.0")}}[1]
10, parcial157.1
Disponible en los workers{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatGeckoMobile("37.0")}}{{CompatUnknown}}{{CompatVersionUnknown}}{{CompatUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
CaracterísticaAndroidEdgeFirefox Mobile (Gecko)Firefox OSIE PhoneOpera MobileSafari Mobile
Soporte básico4.4{{CompatVersionUnknown}}{{CompatGeckoMobile("22.0")}}
+ {{CompatGeckoMobile("52.0")}}[1]
1.0.110228
Disponible en los workers{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatGeckoMobile("37.0")}}{{CompatVersionUnknown}}{{CompatUnknown}}{{CompatVersionUnknown}}{{CompatUnknown}}
+
+ +

[1] indexedDB se define ahora en el mixin {{domxref("WindowOrWorkerGlobalScope")}}.

+ +

Ver también

+ +
    +
  • Utilización de IndexedDB
  • +
  • Iniciando transacciones: {{domxref("IDBDatabase")}}
  • +
  • Usando transacciones: {{domxref("IDBTransaction")}}
  • +
  • Estableciendo un rango de claves: {{domxref("IDBKeyRange")}}
  • +
  • Recuperación y edición de tus datos: {{domxref("IDBObjectStore")}}
  • +
  • Utilización de cursores: {{domxref("IDBCursor")}}
  • +
  • Ejemplo de referencia: To-do Notifications (ver ejemplo live.)
  • +
diff --git a/files/es/web/api/issecurecontext/index.html b/files/es/web/api/issecurecontext/index.html new file mode 100644 index 0000000000..a1e631007e --- /dev/null +++ b/files/es/web/api/issecurecontext/index.html @@ -0,0 +1,87 @@ +--- +title: WindowOrWorkerGlobalScope.isSecureContext +slug: Web/API/isSecureContext +translation_of: Web/API/WindowOrWorkerGlobalScope/isSecureContext +original_slug: Web/API/WindowOrWorkerGlobalScope/isSecureContext +--- +

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

+ +

La propiedad de sólo-lectura isSecureContext, de la interface  {{domxref("WindowOrWorkerGlobalScope")}} Devuelve un booleano indicando si el contexto actual es seguro (true) or not (false).

+ +

Sintaxis

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

Valor

+ +

Un {{domxref("Boolean")}}.

+ +

Especificaciones

+ + + + + + + + + + + + + + +
EspecificaciónEstadoComentario
{{SpecName('Secure Contexts', 'webappapis.html#dom-origin', 'WindowOrWorkerGlobalScope.isSecureContext')}}{{Spec2('Secure Contexts')}}Definición inicial.
+ +

Compatibilidad de Navegadores

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + +
CaracterísticaChromeFirefox (Gecko)Internet ExplorerOperaSafari
Soporte básico{{CompatChrome(55)}}{{CompatGeckoDesktop(52)}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
CaracterísticaAndroid WebviewChrome para AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Soporte básico{{CompatChrome(55)}}{{CompatChrome(55)}}{{CompatGeckoMobile(52)}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
+
diff --git a/files/es/web/api/setinterval/index.html b/files/es/web/api/setinterval/index.html new file mode 100644 index 0000000000..381711900a --- /dev/null +++ b/files/es/web/api/setinterval/index.html @@ -0,0 +1,693 @@ +--- +title: WindowTimers.setInterval() +slug: Web/API/setInterval +tags: + - API + - DOM + - Gecko + - Intervalos + - Method + - Temporizadores + - Temporizadores de JavaScript + - WindowTimers + - setInterval +translation_of: Web/API/WindowOrWorkerGlobalScope/setInterval +original_slug: Web/API/WindowOrWorkerGlobalScope/setInterval +--- +
{{APIRef("HTML DOM")}}
+ +
Ejecuta una función o un fragmento de código de forma repetitiva cada vez que termina el periodo de tiempo determinado. Devuelve un ID de proceso.
+ +
+ +

Sintaxis

+ +
var procesoID = window.setInterval(función, intervaloDeTiempo[, parámetro1, parámetro2, ... , parámetroN]);
+var procesoID = window.setInterval(código, intervaloDeTiempo);
+
+ +

Parámetros

+ +
+
función
+
La {{jsxref("function")}} que será ejecutada cada intervaloDeTiempo milisegundos.
+
código
+
Una sintaxis opcional permite introducir una cadena en lugar de una función, la cual es evaluada y ejecutada cada intervaloDeTiempo milisegundos. Se recomienda evitar esta sintaxis por la misma razón por la que el comando {{jsxref("eval", "eval()")}} conlleva problemas de seguridad.
+
intervaloDeTiempo
+
El tiempo en milisegundos (1/1000 de segundo, ms) que se debe esperar entre cada ejecución de la función o del código. Si el valor es menor que 10, se usará 10 en su lugar. El tiempo entre cada ejecución puede ser mayor al que indicamos, para mayor información puedes revisar el siguiente artículo: {{SectionOnPage("/en-US/docs/Web/API/WindowTimers/setTimeout", "Reasons for delays longer than specified")}}.
+
+
El parámetro intervaloDeTiempo es convertido en un entero de 32 bits con signo en el IDL, por lo que el valor más grande que puede tener es 2,147,483,647 milisegundos, aproximadamente 24.8 días.
+
+
parámetro1, ..., parámetroN {{optional_inline}}
+
Parámetros adicionales que se pasan a la función a ejecutar.
+
+ +
+

En Internet Explorer 9 y anteriores no es posible pasar más parámetros mediante esta sintaxis. Si quieres activar esta funcionalidad en dichos navegadores deberás usar un polyfill (entra en la sección Callback arguments).

+
+ +

Valor de Retorno

+ +

El valor de retorno procesoID es un valor numérico distinto de cero que identifica al temporizador que fue creado al llamar setInterval(); este valor puede ser usado como parámetro en la función {{domxref("Window.clearInterval()")}} para detener el temporizador. Las funciones setInterval() y {{domxref("WindowTimers.setTimeout", "setTimeout()")}} comparten la misma pila de IDs, por lo que, técnicamente, los comandos clearInterval() y {{domxref("WindowTimers.clearTimeout", "clearTimeout()")}} pueden usarse indiscriminadamente. Sin embargo, por motivos de claridad y mantenimiento, es importante usarlos como corresponde.

+ +
+

Nota: El argumento intervaloDeTiempo se convierte aun entero con signo de 32 bits. Esto limita efectivamente al intervaloDeTiempo a valores de 2147483647 ms, ya que se especifica como entero con signo en el IDL.

+
+ +

Ejemplos

+ +

Ejemplo 1: Sintaxis básica

+ +

El siguiente ejemplo muestra la sintaxis básica.

+ +
var intervalID = window.setInterval(miFuncion, 500, 'Parametro 1', 'Parametro 2');
+
+function miFuncion(a,b) {
+  // Aquí va tu código
+  // Los parámetros son opcionales completamente
+  console.log(a);
+  console.log(b);
+}
+
+ +

Ejemplo 2: Alternando dos colores

+ +

El siguiente ejemplo se llama a la función flashtext() una vez por segundo hasta que se presiona el botón Detener.

+ +
<!DOCTYPE html>
+<html>
+<head>
+  <meta charset="UTF-8" />
+  <title>Ejemplo de setInterval/clearInterval</title>
+  <script>
+     var nIntervId;
+
+     function cambiaDeColor() {
+        nIntervId = setInterval(flasheaTexto, 1000);
+     }
+
+     function flasheaTexto() {
+        var oElem = document.getElementById('mi_mensaje');
+        oElem.style.color = oElem.style.color == 'red' ? 'blue' : 'red';
+        //oElem.style.color ... es un operador ternario o condicional
+     }
+
+     function detenerCambioDeColor() {
+        clearInterval(nIntervId);
+     }
+  </script>
+</head>
+<body onload="cambiaDeColor();">
+  <div id="mi_mensaje">
+    <p>¡Hola mundo!</p>
+  </div>
+  <button onclick="detenerCambioDeColor();">Detener</button>
+</body>
+</html>
+
+ +

Ejemplo 3: Simulando una máquina de escribir

+ +

El siguiente ejemplo simula una máquina de escribir, primero borra el contenido de una lista de nodos (NodeList) que coinciden con un grupo de selectores y después lo escribe lentamente.

+ +
<!DOCTYPE html>
+<html>
+<head>
+<meta charset="UTF-8" />
+<title>Máquina de Escribir con JavaScript</title>
+<script>
+  function maquinaEscribir (sSelector, nRate) {
+
+      function limpiar () {
+        clearInterval(nIntervId);
+        bTyping = false;
+        bStart = true;
+        oCurrent = null;
+        aSheets.length = nIdx = 0;
+      }
+
+      function desplazarse (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]];
+
+          desplazarse(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 mecanografear () {
+        if (sPart.length === 0 && desplazarse(aSheets[nIdx], 0, true) && nIdx++ === aSheets.length - 1) { limpiar(); return; }
+
+        oCurrent.nodeValue += sPart.charAt(0);
+        sPart = sPart.slice(1);
+      }
+
+      function Hoja (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 Hoja(this.parts[nChild]);
+        }
+      }
+
+      var
+        nIntervId, oCurrent = null, bTyping = false, bStart = true,
+        nIdx = 0, sPart = "", aSheets = [], aMap = [];
+
+      this.rate = nRate || 100;
+
+      this.ejecuta = 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 Hoja(aItems[nItem]));
+            /* Uncomment the following line if you have previously hidden your elements via CSS: */
+            // aItems[nItem].style.visibility = "visible";
+          }
+
+          bStart = false;
+        }
+
+        nIntervId = setInterval(mecanografear, this.rate);
+        bTyping = true;
+      };
+
+      this.pausa = function () {
+        clearInterval(nIntervId);
+        bTyping = false;
+      };
+
+      this.finaliza = function () {
+        oCurrent.nodeValue += sPart;
+        sPart = "";
+        for (nIdx; nIdx < aSheets.length; desplazarse(aSheets[nIdx++], 0, false));
+        limpiar();
+      };
+  }
+
+    /* usage: */
+    var oTWExample1 = new maquinaEscribir(/* elements: */ "#article, h1, #info, #copyleft", /* frame rate (optional): */ 15);
+
+    /* default frame rate is 100: */
+    var oTWExample2 = new maquinaEscribir("#controls");
+
+    /* you can also change the frame rate value modifying the "rate" property; for example: */
+    // oTWExample2.rate = 150;
+
+    onload = function () {
+      oTWExample1.ejecuta();
+      oTWExample2.ejecuta();
+    };
+</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.ejecuta();">Ejecutar</span> | <span class="intLink" onclick="oTWExample1.pausa();">Pausar</span> | <span class="intLink" onclick="oTWExample1.finaliza();">Terminar</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>Maquina de Escribir en JavaScript </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>
+
+ +

Observa este ejemplo en acción. Ver más: clearInterval().

+ +

Argumentos de Callback

+ +

Como se mencionó previamente Internet Explorer version 9 y anteriores no soportan el pasar argumentos a la función Callback en setTimeout() ni en setInterval(). El siguiente código específico de Internet Explorer muestra un método de superar esta limitante. Para usarlo basta añadir el código marcado al inicio de tu script.

+ +
/*\
+|*|
+|*|  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;
+}
+
+ +

Otra posible solución es el usar funciones anónimas para llamar al Callback, aunque esta solución es un poco más cara. Ejemplo:

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

También puedes hacer uso de function's bind. Ejemplo:

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

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

+ +

A partir de Gecko 5.0 {{geckoRelease("5.0")}}, los intervalos no se disparan más de una vez por segundo en las pestañas inactivas.

+ +

Problemas usando "this"

+ +

Cuando pasas el método de un objeto a la función setInterval() éste es invocado fuera de su contexto. Esto puede crear un valor de this que puede no ser el esperado. Este problema es abordado en detalle en JavaScript reference.

+ +

Explicación

+ +

Cuando setInterval() o setTimeOut() ejecuta un determinado código o función, ésta corre en un contexto de ejecución separado al de la función en la que se creó dicho temporizador. Por esta razón a la palabra clave this se le asigna el valor del objeto window (o el objeto global), no es igual que usar this dentro de una fuinción que invoque a setTimeOut(). Observa el siguiente ejemplo (que utiliza setTimeOut() en lugar de setInterval() – el problema, de hecho, es el mismo para ambos temporizadores):

+ +
miArreglo = ["cero", "uno", "dos"];
+
+miArreglo.miMetodo = function (sPropiedad) {
+    alert(arguments.length > 0 ? this[sPropiedad] : this);
+};
+
+miArreglo.miMetodo(); // imprime "cero,uno,dos"
+miArreglo.miMetodo(1); // imprime "uno"
+setTimeout(miArreglo.miMetodo, 1000); // imprime "[object Window]" despues de 1 segundo
+setTimeout(miArreglo.miMetodo, 1500, "1"); // imprime "undefined" despues de 1,5 segundos
+// tratemos de pasar el objeto 'this'
+setTimeout.call(miArreglo, miArreglo.miMetodo, 2000); // error: "NS_ERROR_XPC_BAD_OP_ON_WN_PROTO: Illegal operation on WrappedNative prototype object"
+setTimeout.call(miArreglo, miArreglo.miMetodo, 2500, 2); // same error
+ +

Como puedes ver no hay forma de pasar el objeto this a la función de Callback en la versión anterior de JavaScript.

+ +

Una posible solución

+ +

Una posible alternativa para resolver ésto es reemplazar las dos funciones globales nativas setTimeout() y setInterval() con las siguientes funciones no nativas que permiten su ejecución a través del método Function.prototype.call. El siguiente ejemplo muestra una posible sustitución:

+ +
// Permite el pase del objeto 'this' a través de temporizadores JavaScript
+
+var __nativeST__ = window.setTimeout, __nativeSI__ = window.setInterval;
+
+window.setTimeout = function (vCallback, nDelay /*, argumentoAPasar1, argumentuAPasar2, 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 /*, argumentoAPasar1, argumentoAPasar2, etc. */) {
+  var oThis = this, aArgs = Array.prototype.slice.call(arguments, 2);
+  return __nativeSI__(vCallback instanceof Function ? function () {
+    vCallback.apply(oThis, aArgs);
+  } : vCallback, nDelay);
+};
+
+ +
Estos dos reemplazos también permiten el camino estándar en HTML5 de pasar argumentos arbitrarios a las funciones de Callback de los temporizadores dentro de IE. Por lo tanto, pueden utilizarse como rellenos (polyfills) no estándar. Para más información vea callback arguments paragraph.
+ +

Prueba de nueva funcionalidad:

+ +
miArreglo = ["cero", "uno", "dos"];
+
+miArreglo.miMetodo = function (sProperty) {
+    alert(arguments.length > 0 ? this[sProperty] : this);
+};
+
+setTimeout(alert, 1500, "Hola Mundo!"); // la utilizacion estandar de setTimeout y de setInterval se mantiene, pero...
+setTimeout.call(miArreglo, miArreglo.miMetodo, 2000); // imprime "cero,uno,dos" despues de 2 segundos
+setTimeout.call(miArreglo, miArreglo.miMetodo, 2500, 2); // imprime "dos" despues de 2,5 segundos
+
+ +

Otra solución más compleja está en la siguiente liga de framework.

+ +
JavaScript 1.8.5 introduce el método Function.prototype.bind(), el cual permite especificar el valor de this para todas sus llamadas en una determinada función. Esto permite sobrellevar facilmente diferentes problemas de contexto con el uso de la palabra this. También, ES2015 soporta arrow functions, dentro del lenguaje nos permite escribir cosas como setInterval( () => this.myMethod) si estamos dentro del método de miArreglo .
+ +

MiniDaemon - Un framework para administrar temporizadores

+ +

En proyectos que requieren muchos temporizadores puede volverse complicado el seguimiento de todos los eventos generados. Una forma de facilitar la administración de timers es guardando sus estados en un objeto. El siguiente ejemplo muestra este tipo de abstracción, la arquitectura del constructor evita explicitamente el uso de cerraduras. También ofrece un camino alternativo para pasar el objeto this a la función de Callback (observa la sección Problemas usando "this" para más detalles). Puedes consultar también el siguiente código en GitHub.

+ +
Para una versión más modular de este (Daemon)puedes verlo en JavaScript Daemons Management. Aquí encontrarás una versión mas complicada que se reduce a una colección escalable de métodos para el constructor Daemon. Éste constructor no es más que un clon del  MiniDaemon con soporte para las funciones init y onstart declarables durante la instanciación del mismo. Por esto el MiniDaemon framework se mantiene como el camino recomendado para realizar animaciones simples.
+ +

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 pasa argumentos a la función callback. Si quieres trabajar con ellos en navegadores que no soportan nativamente esta característica, usa uno de los métodos propuestos arriba.
+ +

Sintaxis

+ +

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

+ +

Descripción

+ +

Regresa un Objecto que contiene la información necesaria para una animación (como el objeto this, la función de Callback, la duración y el frame-rate).

+ +

Parámetros

+ +
+
thisObject
+
El valor de la palabra this sobre el cual funcionará la función de Callback. Puede ser un objecto o null.
+
callback
+
La función que se invocará repetidas veces. Dicha función se invocará con tres parámetros: index que corresponde al valor iterativo de cada invocación, length que es el número total de invocaciones asignadas al daemon (puede ser un valor finito o Infinity) y backwards (valor booleano que expresa cuando el valor de index es creciente o decreciente). Es similar a callback.call(thisObject, index, length, backwards). Si la función de Callback regresa un valor false el deamon se detiene.
+
rate (optional)
+
El tiempo minimo en milisegundos que transcurre entre cada invocación. El valor por omisión es 100.
+
length (optional)
+
El número total de invocaciones. Puede ser un valor entero positivo o Infinity. El valor por omisión es Infinity.
+
+ +

Propiedades de la intancia MiniDaemon 

+ +
+
myDaemon.owner
+
El objeto this sobre el cual se ejecuta el daemon (lectura/escritura). Puede ser un objecto o null.
+
myDaemon.task
+
La función que se invocará repetidas veces. Dicha función se invocará con tres parámetros: index que corresponde al valor iterativo de cada invocación, length que es el número total de invocaciones asignadas al daemon (puede ser un valor finito o Infinity) y backwards (valor booleano que expresa cuando el valor de index es creciente o decreciente). Es similar a callback.call(thisObject, index, length, backwards). Si la función de Callback regresa un valor false el deamon se detiene.
+
myDaemon.rate
+
El tiempo minimo en milisegundos que transcurre entre cada invocación. El valor por omición es 100 (lectura/escritura).
+
myDaemon.length
+
El número total de invocaciones. Puede ser un valor entero positivo o Infinity. El valor por omición es Infinity (lectura/escritura).
+
+ +

MiniDaemon instances methods

+ +
+
myDaemon.isAtEnd()
+
Regresa un valor boleano que expresa cuando el daemon está en posición de inicio/fin o no.
+
myDaemon.synchronize()
+
Sincroniza el tiempo de un deamon iniciado con el tiempo de su invocación.
+
myDaemon.pause()
+
Pausa el deamon.
+
myDaemon.start([reverse])
+
Inicia el daemon hacia adelante "forward" (el indice de cada invocación se incrementa) o hacia atrás "backwards" (el índice de cada invocación se decrementa).
+
+ +

Métodos del objeto global del MiniDaemon

+ +
+
MiniDaemon.forceCall(minidaemon)
+
Fuerza una sola función callback a la función minidaemon.task  en lugar del hecho de que se ha alcanzado el final o no. En cualquier caso la propiedad INDEX interna crece o decrece según la dirección del proceso.
+
+ +

Ejemplo de uso

+ +

Tu página 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>
+ +

Prueba este ejemplo

+ +

Notas

+ +

La función setInterval() es usada frecuentemente para asignar una pausa para ejecutar funciones recurrentes, como por ejemplo pintar el siguiente cuadro de una animación.

+ +

Puedes cancelar el ciclo iniciado por un setInterval() usando el comando window.clearInterval().

+ +

Si solo deseas ejecutar el ciclo una sola vez despues de una pausa usa en su lugar la función window.setTimeout().

+ +

Asegúrate que el tiempo de ejecución sea menor que la frecuencia

+ +

Si existe la posibilidad de que tu función o el código a ejecutarse una y otra vez exeda el tiempo marcado en cada intervalo es recomendado que uses recursivamente el nombre de tu función usando window.setTimeout. Por ejemplo, si usas setInterval para hacer llamadas a un servidor remoto cada 5 segundos, la latencia en la red, un servidor que no responde, o cualquier otro tipo de contratiempo puede generar una pausa mayor a la que indicaste. De esta forma terminarás con solicitudes XHR apiladas que no se resolverán necesariamente en orden.

+ +

En estos casos llamadas con un patrón de setTimeout() recursivo es preferible:

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

En este fragmento de código, la función loop() es declarada y es ejecutada inmediatamente. La función loop() es invocada de forma recursiva dentro de setTimeout() despues de cada ejecución. Si bien este patrón no garantiza una ejecución a intervalos fijos, si garantiza que nunca se ejecutará un paso sin que se haya finalizado el anterior. 

+ +

Especificaciones

+ + + + + + + + + + + + + + +
EspecificacionesEstatusComentarios
{{SpecName("HTML WHATWG", "webappapis.html#dom-setinterval", "WindowTimers.setInterval()")}}{{Spec2("HTML WHATWG")}}Definición inicial (DOM Level 0)
+ +

Compatibilidad

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + +
CaracterísticaChromeFirefox (Gecko)[2]Internet ExplorerOperaSafari
Soporte básico1.0{{CompatGeckoDesktop("1")}}4.04.01.0
Soporta parámetros para callback[1]{{CompatVersionUnknown}}{{CompatVersionUnknown}}10.0{{CompatVersionUnknown}}{{CompatUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
CaracterísticaAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Soporte básico1.01.0{{CompatGeckoMobile("1")}}6.06.01.0
Soporta parámetros para callback[1]{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
+
+ +

[1] Whether it supports the optional parameters when in its first form or not.

+ +

[2] Anterior a Firefox 13, Firefox pasaba un parametro adicional al callback, indicando el "actual lateness" del timeout en milisegundos. Este parámetro no estandar dejó de usarse en versiones posteriores a Firefox 13. No es recomendable que extensiones basadas en XPCOM para Firefox usen setInterval(), ya que las actualizaciones pueden causar el que el objeto {{domxref("Window")}} se actualice perdiendo los temporizadores. Deberás usar en su lugar {{interface("nsITimer")}}.

+ +

Ver más

+ +
    +
  • JavaScript timers
  • +
  • {{domxref("WindowTimers.setTimeout")}}
  • +
  • {{domxref("WindowTimers.clearTimeout")}}
  • +
  • {{domxref("WindowTimers.clearInterval")}}
  • +
  • {{domxref("window.requestAnimationFrame")}}
  • +
  • Daemons management
  • +
diff --git a/files/es/web/api/settimeout/index.html b/files/es/web/api/settimeout/index.html new file mode 100644 index 0000000000..aa531c471d --- /dev/null +++ b/files/es/web/api/settimeout/index.html @@ -0,0 +1,341 @@ +--- +title: WindowOrWorkerGlobalScope.setTimeout +slug: Web/API/setTimeout +tags: + - API + - HTML DOM + - WindowOrWorkerGlobalScope + - setTimeout +translation_of: Web/API/WindowOrWorkerGlobalScope/setTimeout +original_slug: Web/API/WindowOrWorkerGlobalScope/setTimeout +--- +
{{APIRef("HTML DOM")}}
+ +

El método setTimeout() del mixin {{domxref("WindowOrWorkerGlobalScope")}} establece un temporizador que ejecuta una función o una porción de código después de que transcurre un tiempo establecido.

+ + +

Sintaxis

+ +
var idTemporizador = scope.setTimeout(funcion[, retraso, parametro1, parametro2, ...]);
+var idTimeout = scope.setTimeout(funcion[, retraso]);
+var idTimeout = scope.setTimeout(codigo[, retraso]);
+
+ +

Parámetros

+ +
+
funcion
+
Una {{jsxref("function")}} para ejecutar después de que expire el temporizador.
+
codigo
+
Una sintaxis opcional que le permite incluir una cadena en lugar de una función, la cual es compilada y ejecutada cuando el temporizador expira. Esta sintaxis no se recomienda por las mismas razones que hacen del uso de {{jsxref("Global_Objects/eval", "eval()")}} un riesgo de seguridad.
+
retraso {{optional_inline}}
+
Tiempo, en milisegundos  (milésimas de segundo), que el temporizador debe esperar antes de ejecutar la función o el código. Si se omite este parámetro se usa el valor 0. Tenga en cuenta que el retraso real puede ser más prolongado; ver más abajo {{anch("Reasons for delays longer than specified")}}.
+
param1, ..., paramN {{optional_inline}}
+
Parámetros adicionales que se pasan a la función especificada por  func una vez el temporizador expira.
+
+ +
Nota: Pasar parámetros adicionales a la función en la primera sintaxis no funciona en Internet Explorer 9 o inferior. Si quiere habilitar esta funcionalidad en ese navegador,  debe usar un código de compatibilidad (vea la sección Callback arguments).
+ +

Valor retornado

+ +

El valor retornado IDtemporizador es númerico y no es cero; identifica el temporizador creado con la llamada a setTimeout(); este valor puede pasarse a {{domxref("WindowOrWorkerGlobalScope.clearTimeout()")}} para cancelar el temporizador.

+ +

Puede ser útil advertir que  setTimeout() y {{domxref("WindowOrWorkerGlobalScope.setInterval", "setInterval()")}} comparten la misma piscina de IDs, y que tanto clearTimeout() como {{domxref("WindowOrWorkerGlobalScope.clearInterval", "clearInterval()")}} pueden intercambiarse.  Por claridad, sin embargo,  debe hacerlos coincidir para evitar confusiones cuando mantenga su código.

+ +

Ejemplo

+ +

El siguiente ejemplo establece dos botenes simples en una página web y los engancha a las rutinas setTimeout() y clearTimeout(). Presionando el primer botón establecerá un temporizador que llama un diálogo de alerta después de dos segundos y guarda el id del temporizador para usarlo con clearTimeout(). Opcionalmente puede cancelar este temporizador presionando el segundo botón.

+ +

Contenido HTML

+ +
<p>Ejemplo funcional</p>
+<button onclick="delayedAlert();">Muestra una caja de alerta después de dos segundos</button>
+<p></p>
+<button onclick="clearAlert();">Cancela la alerta antes de que ocurra</button>
+
+ +

Contenido JavaScript

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

{{ EmbedLiveSample('Example') }}

+ +

Vea también clearTimeout() example.

+ +

Callback arguments

+ +

Si necesita pasar un argumento a su función callback, pero necesita que funcione en Internet Explorer, que no soporta el envío de parámetros adicionales (ni con setTimeout()setInterval()) usted puede incluir este código de compatibilidad IE-specific que habilitará la funcionalidad estándar de HTML5 para pasar los parámetros adicionales en ese navegador para ambos temporizadores solamente insertandolo al inicio de sus scripts.

+ +
/*\
+|*|
+|*|  IE-specific polyfill which enables the passage of arbitrary arguments to the
+|*|  callback functions of JavaScript timers (HTML5 standard syntax).
+|*|
+|*|  https://developer.mozilla.org/en-US/docs/DOM/window.setInterval
+|*|
+|*|  Syntax:
+|*|  var timeoutID = window.setTimeout(func, delay, [param1, param2, ...]);
+|*|  var timeoutID = window.setTimeout(code, delay);
+|*|  var intervalID = window.setInterval(func, delay[, param1, param2, ...]);
+|*|  var intervalID = window.setInterval(code, delay);
+|*|
+\*/
+
+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;
+}
+
+ +

Arreglo solo para IE

+ +

Si quiere una solución completamente no intrusiva con otros navegadores móviles o de escritorio, incluyendo IE 9 y superior, puede usar los comentarios condicionales de JavaScript:

+ +
/*@cc_on
+  // conditional IE < 9 only fix
+  @if (@_jscript_version <= 6)
+  (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.apply(this,a)},t)}});
+  @end
+@*/
+
+ +

O usar un enfoque más limpio basado en el condicional para IE de HTML:

+ +
<!--[if lt 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.apply(this,a)},t)}
+});
+</script><![endif]-->
+
+ +

Otra posibilidad es usar una función anónima para llamar el callback, pero esta solución es un poco más costosa. Ejemplo:

+ +
var intervalID = setTimeout(function() { myFunc("uno", "dos", "tres"); }, 1000);
+
+ +

Sin embargo, otra posibilidad es usar function's bind. Ejemplo:

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

El problema "this"

+ +

Cuando pasa un método a setTimeout() (o cualquier otra función , por el estilo), podría ser invocada con el valor de this equivocado. Este problema es explicado en detalle en la referencia de JavaScript.

+ +

Explicación

+ +

El código ejecutado por setTimeout() corre en un contexto de ejecución diferente al de la función por la que fue llamado. Como consecuencia, la palabra clave this para la función llamada será asignado al objeto window (o global); no tendrá el mismo valor del this de la función que llamó al setTimeout. Vea el siguiente ejemplo:

+ +
myArray = ["cero", "uno", "dos"];
+myArray.myMethod = function (sProperty) {
+    alert(arguments.length > 0 ? this[sProperty] : this);
+};
+
+myArray.myMethod(); // imprime "cero,uno,dos"
+myArray.myMethod(1); // imprime "uno"
+setTimeout(myArray.myMethod, 1000); // imprime "[object Window]" después de 1 segundo
+setTimeout(myArray.myMethod, 1500, "1"); // imprime "undefined" después de 1.5 segundos
+// intentemos pasar el objeto 'this'
+setTimeout.call(myArray, myArray.myMethod, 2000); // error: "NS_ERROR_XPC_BAD_OP_ON_WN_PROTO: Illegal operation on WrappedNative prototype object"
+setTimeout.call(myArray, myArray.myMethod, 2500, 2); // mismo error
+ +

Como puedes ver no hay forma de pasar el objeto this a la función callback.

+ +

Una posible solución

+ +

Una posible forma de resolver el problema del "this" es reemplazar las dos funciones globales nativas setTimeout() or setInterval()por dos no-nativas  que permitan su invocación a través del método Function.prototype.call. El siguiente ejemplo muestra un posible reemplazo:

+ +
// 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);
+};
+ +
Nota: Estos dos reemplazos habilitarán el estándar HTML5 para el paso de argumentos arbitrarios a las funciones callback de los temporizadores en IE. Pueden usarse como polyfills también. Vea el párrafo Callback arguments.
+ +

Prueba de la nueva característica:

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

No hay soluciones nativas ad hoc a este problema.

+ +
Nota: JavaScript 1.8.5 introduce el método Function.prototype.bind(, que permite especificar el valor que debería usarse como this para todas las llamadas a una función dada. Esto permite evitar fácilmente los problemas en los que no es claro que será, dependiendo del contexto desde el cual la función sea llamada.
+ +

Notas

+ +

Puede cancelar el temporizador usando window.clearTimeout(). Si desea tener una función llamada repetidamente (p.e., cada N milisegundos), considere usar window.setInterval().

+ +

Es importante notar que la función o fragmento de código no puede ser ejecutado hasta que el hilo que llamó setTimeout()haya terminado.

+ +

Pasando cadenas literales

+ +

Pasando una cadena en vez de una función a setTimeout()pasa lo mismo que al usar eval.

+ +
// Correcto
+window.setTimeout(function() {
+    alert("Hello World!");
+}, 500);
+
+// Incorrecto
+window.setTimeout("alert(\"Hello World!\");", 500);
+
+
+ +

Las cadenas literales son evaluadas en el contexto global, así que los símbolos locales en el contexto donde setTimeout() fue llamado no estarán disponibles cuando la cadena es evaluada como código.

+ +

Minimum/ maximum delay and timeout nesting

+ +

Historically browsers implement setTimeout() "clamping": successive setTimeout() calls with delay smaller than the "minimum delay" limit are forced to use at least the minimum delay. The minimum delay, DOM_MIN_TIMEOUT_VALUE, is 4 ms (stored in a preference in Firefox: dom.min_timeout_value), with a DOM_CLAMP_TIMEOUT_NESTING_LEVEL of 5ms.

+ +

In fact, 4ms is specified by the HTML5 spec and is consistent across browsers released in 2010 and onward. Prior to {{ geckoRelease("5.0") }}, the minimum timeout value for nested timeouts was 10 ms.

+ +

In addition to "clamping", the timeout can also fire later when the page (or the OS/browser itself) is busy with other tasks.

+ +

To implement a 0 ms timeout in a modern browser, you can use {{ domxref("window.postMessage()") }} as described here.

+ +

Browsers including Internet Explorer, Chrome, Safari, and Firefox store the delay as a 32-bit signed Integer internally. This causes an Integer overflow when using delays larger than 2147483647, resulting in the timeout being executed immediately.

+ +

Inactive tabs

+ +

In {{ geckoRelease("5.0") }} and Chrome 11, timeouts are clamped to firing no more often than once per second (1000ms) in inactive tabs; see {{ bug(633421) }} for more information about this in Mozilla or crbug.com/66078 for details about this in Chrome.

+ +

Compatibilidad de navegadores

+ +

{{ CompatibilityTable() }}

+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + +
CaracterísticaChromeFirefox (Gecko)Internet ExplorerOperaSafari
Soporte básico1.0{{ CompatGeckoDesktop("1") }}4.04.01.0
Soporta parámetros para callback*1{{ CompatVersionUnknown }}{{ CompatVersionUnknown }}10.0{{ CompatVersionUnknown }}{{ CompatUnknown }}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
CaracterísticaAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Soporte básico1.01.0{{ CompatGeckoMobile("1") }}6.06.01.0
Soporta parámetros para callback*1{{ CompatUnknown }}{{ CompatUnknown }}{{ CompatUnknown }}{{ CompatUnknown }}{{ CompatUnknown }}{{ CompatUnknown }}
+
+ +

*1 Whether it supports the optional parameters when in its first form or not.

+ +

Especificación

+ +

Parte del DOM nivel 0, como se especifica en HTML5.

+ +

Vea también

+ + diff --git a/files/es/web/api/windoworworkerglobalscope/atob/index.html b/files/es/web/api/windoworworkerglobalscope/atob/index.html deleted file mode 100644 index 446f7e2df9..0000000000 --- a/files/es/web/api/windoworworkerglobalscope/atob/index.html +++ /dev/null @@ -1,112 +0,0 @@ ---- -title: WindowBase64.atob() -slug: Web/API/WindowOrWorkerGlobalScope/atob -translation_of: Web/API/WindowOrWorkerGlobalScope/atob -original_slug: Web/API/WindowBase64/atob ---- -

{{APIRef}}

- -

La función WindowBase64.atob() descodifica una cadena de datos que ha sido codificada utilizando la codificación en base-64. Puedes utilizar el método {{domxref("window.btoa()")}} para codificar y transmitir datos que, de otro modo podrían generar problemas de comunicación. Luego de ser transmitidos se puede usar el método window.atob() para decodificar los datos de nuevo. Por ejemplo, puedes codificar, transmitir y decodificar los caracteres de control como valores ASCII 0 a 31.

- -

For use with Unicode or UTF-8 strings, see this note at Base64 encoding and decoding and this note at window.btoa().

- -

Syntax

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

Example

- -
var encodedData = window.btoa("Hello, world"); // encode a string
-var decodedData = window.atob(encodedData); // decode the string
- -

Specifications

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

Browser compatibility

- -
{{CompatibilityTable}}
- -
- - - - - - - - - - - - - - - - - - - -
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Basic support{{CompatVersionUnknown}}{{CompatGeckoDesktop(1)}}[1][2]10{{CompatVersionUnknown}}{{CompatVersionUnknown}}
-
- -
- - - - - - - - - - - - - - - - - - - -
FeatureAndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{CompatVersionUnknown}}{{CompatGeckoMobile(1)}}{{CompatNo}}{{CompatUnknown}}{{CompatVersionUnknown}}
-
- -

[1]  atob() is also available to XPCOM components implemented in JavaScript, even though window is not the global object in components.

- -

[2] Starting with Firefox 27, this atob() method ignores all space characters in the argument to comply with the latest HTML5 spec. ({{ bug(711180) }})

- -

See also

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

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

- -

La propiedad de sólo-lectura caches, de la interfaz {{domxref("WindowOrWorkerGlobalScope")}}, devuelve el objeto {{domxref("CacheStorage")}} asociado al contexto actual. Este objeto habilita funcionalidades como guardar assets para su utilización offline, y generar respuestas personalizadas a las peticiones.

- -

Sintaxis

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

Valor

- -

Un objeto {{domxref("CacheStorage")}}.

- -

Ejemplo

- -

El siguiente ejemplo muestra la forma en la que utilizarías una cache en un contexto de service worker para guardar assets offline.

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

Especificaciones

- - - - - - - - - - - - - - - - - - - -
EspecificaciónEstadoComentario
{{SpecName('Service Workers', '#self-caches', 'caches')}}{{Spec2('Service Workers')}}Definido en un WindowOrWorkerGlobalScope parcial en la última especificación.
{{SpecName('Service Workers')}}{{Spec2('Service Workers')}}Definición inicial.
- -

Compatibilidad de Navegadores

- -

{{CompatibilityTable}}

- -
- - - - - - - - - - - - - - - - - - - -
CaracterísticaChromeFirefox (Gecko)Internet ExplorerOperaSafari
Soporte Básico40.0{{CompatGeckoDesktop(42)}}
- {{CompatGeckoDesktop(52)}}[1]
{{CompatNo}}{{CompatUnknown}}{{CompatNo}}
-
- -
- - - - - - - - - - - - - - - - - - - - - -
CaracterísticaAndroidChrome para AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Soporte Básico{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatGeckoMobile(42)}}
- {{CompatGeckoMobile(52)}}[1]
{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
-
- -

[1] las caches se definen ahora en el mixin {{domxref("WindowOrWorkerGlobalScope")}}.

- -

Ver también

- - diff --git a/files/es/web/api/windoworworkerglobalscope/clearinterval/index.html b/files/es/web/api/windoworworkerglobalscope/clearinterval/index.html deleted file mode 100644 index c984baf637..0000000000 --- a/files/es/web/api/windoworworkerglobalscope/clearinterval/index.html +++ /dev/null @@ -1,44 +0,0 @@ ---- -title: WindowTimers.clearInterval() -slug: Web/API/WindowOrWorkerGlobalScope/clearInterval -translation_of: Web/API/WindowOrWorkerGlobalScope/clearInterval -original_slug: Web/API/WindowTimers/clearInterval ---- -
-
{{APIRef("HTML DOM")}}
-
- -

Cancela una acción reiterativa que se inició mediante una llamada a {{domxref("window.setInterval", "setInterval")}}.

- -

Sintaxis

- -
window.clearInterval(intervalID)
-
- -

intervalID es el identificador de la acción reiterativa que se desea cancelar. Este ID se obtiene a partir de setInterval().

- -

Ejemplo

- -

Vea el ejemplo de setInterval().

- -

Especificación

- - - - - - - - -
{{SpecName('HTML WHATWG', 'timers.html#timers', 'clearInterval')}}{{Spec2('HTML WHATWG')}}
- -

Vea también

- -
    -
  • JavaScript timers
  • -
  • {{domxref("WindowTimers.setTimeout")}}
  • -
  • {{domxref("WindowTimers.setInterval")}}
  • -
  • {{domxref("WindowTimers.clearTimeout")}}
  • -
  • {{domxref("window.requestAnimationFrame")}}
  • -
  • Daemons management
  • -
diff --git a/files/es/web/api/windoworworkerglobalscope/cleartimeout/index.html b/files/es/web/api/windoworworkerglobalscope/cleartimeout/index.html deleted file mode 100644 index e40c77c5b6..0000000000 --- a/files/es/web/api/windoworworkerglobalscope/cleartimeout/index.html +++ /dev/null @@ -1,64 +0,0 @@ ---- -title: window.clearTimeout -slug: Web/API/WindowOrWorkerGlobalScope/clearTimeout -translation_of: Web/API/WindowOrWorkerGlobalScope/clearTimeout -original_slug: Web/API/WindowTimers/clearTimeout ---- -
{{ApiRef}}
- -

Resumen

- -

Borra el retraso asignado por {{domxref("window.setTimeout","window.setTimeout()")}}.

- -

Sintaxis

- -
window.clearTimeout(timeoutID)
-
- -
    -
  • timeoutID es el ID del timeout que desee borrar, retornado por {{domxref("window.setTimeout","window.setTimeout()")}}.
  • -
- -

Ejemplo

- -

Ejecute el script de abajo en el contexto de una página web y haga clic en la página una vez. Verá un mensaje emergente en un segundo. Si permanece haciendo clic en la página cada segundo, la alerta nunca aparece.

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

Notas

- -

Pasar un ID inválido a clearTimeout no tiene ningún efecto (y no lanza una excepción).

- -

Especificación

- -

DOM Nivel 0. Especificado en HTML5.

- -

Vea también

- -
    -
  • JavaScript timers
  • -
  • {{domxref("window.setTimeout")}}
  • -
  • {{domxref("window.setInterval")}}
  • -
  • {{domxref("window.clearInterval")}}
  • -
  • {{domxref("window.requestAnimationFrame")}}
  • -
  • Daemons management
  • -
diff --git a/files/es/web/api/windoworworkerglobalscope/createimagebitmap/index.html b/files/es/web/api/windoworworkerglobalscope/createimagebitmap/index.html deleted file mode 100644 index e24e4b11f4..0000000000 --- a/files/es/web/api/windoworworkerglobalscope/createimagebitmap/index.html +++ /dev/null @@ -1,108 +0,0 @@ ---- -title: self.createImageBitmap() -slug: Web/API/WindowOrWorkerGlobalScope/createImageBitmap -tags: - - API - - Canvas - - DOM - - Referencia - - WindowOrWorkerGlobalScope - - createImageBitmap - - metodo -translation_of: Web/API/WindowOrWorkerGlobalScope/createImageBitmap ---- -
{{APIRef("Canvas API")}}
- -

El método createImageBitmap() crea un bitmap a partir de un recurso especificado, opcionalmente recortado para mostrar únicamente una porción de este. El método existe a nivel global como parte, tanto de las ventanas (window), como de los workers. Este admite una variedad de tipos de entrada, y devuelve una {{domxref("Promise")}} que es resuelta con un {{domxref("ImageBitmap")}}.

- -

Sintaxis

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

Parámetros

- -
-
image
-
Un recurso/imagen origen, que puede uno de los siguientes elementos: {{HTMLElement("img")}}, SVG {{SVGElement("image")}}, {{HTMLElement("video")}}, {{HTMLElement("canvas")}}, {{domxref("HTMLImageElement")}}, {{domxref("SVGImageElement")}}, {{domxref("HTMLVideoElement")}}, {{domxref("HTMLCanvasElement")}}, {{domxref("Blob")}}, {{domxref("ImageData")}}, {{domxref("ImageBitmap")}}, o {{domxref("OffscreenCanvas")}}.
-
sx
-
La coordenada x del rectángulo que será usado para la extracción del ImageBitmap.
-
sy
-
La coordenada y del rectángulo que será usado para la extracción del ImageBitmap.
-
sw
-
La anchura del rectángulo que será usado para extraer el ImageBitmap. El valor podría ser negativo.
-
sh
-
La altura del rectángulo que será usado para extraer el ImageBitmap. El valor podría ser negativo.
-
options {{optional_inline}}
-
Un objeto que proporciona opciones para la extracción de la imagen. Las opciones posibles son: -
    -
  • imageOrientation: Especifica si la imagen debe ser extraida tal y como se muestra, o debe ser volteada verticalmente. Las valores posibles: none (por defecto) o flipY.
  • -
  • premultiplyAlpha: Especifica si los canales de color del mapa de bits generado deben premultiplicarse por el canal alpha. Uno de: none, premultiply, o default (por defecto).
  • -
  • colorSpaceConversion: Especifica si la imagen debe ser decodificada usando conversión del espacio de color. Uno de: none o default (por defecto). El valor default indica que se usará la implementación que haya disponible.
  • -
  • resizeWidth: Un entero largo que especifica la anchura final.
  • -
  • resizeHeight: Un entero largo que especifica la altura final.
  • -
  • resizeQuality: Especifica que algorítmo debe ser usado en el redimensionado para alcanzar las dimensiones deseadas. Uno de estos valores: pixelated, low (por defecto), medium, o high.
  • -
-
-
- -

Valor devuelto

- -

Una {{domxref("Promise")}} que es resuelta con un objeto {{domxref("ImageBitmap")}}, el cual contiene los datos del mapa de bits generado para el rectángulo dado.

- -

Ejemplo

- -

Creando sprites desde un sprite sheet

- -

El siguiente ejemplo carga un sprite sheet, extrae los sprites, y muestra cada uno de ellos en el canvas. Un sprite sheet es una imagen que contiene multiples imágenes más pequeñas, que finalmente son utilizadas de manera individual.

- -
var canvas = document.getElementById('myCanvas'),
-ctx = canvas.getContext('2d'),
-image = new Image();
-
-// Esperar que el sprite sheet se cargue
-image.onload = function() {
-  Promise.all([
-    // Recortar dos sprites del conjunto
-    createImageBitmap(image, 0, 0, 32, 32),
-    createImageBitmap(image, 32, 0, 32, 32)
-  ]).then(function(sprites) {
-    // Pintar cada uno de los sprites en el canvas
-    ctx.drawImage(sprites[0], 0, 0);
-    ctx.drawImage(sprites[1], 32, 32);
-  });
-}
-
-// Cargar el sprite sheet desde un archivo de imagen
-image.src = 'sprites.png';
-
- -

Especificaciones

- - - - - - - - - - - - - - -
EspecificaciónEstado Comentario
{{SpecName('HTML WHATWG', "webappapis.html#dom-createimagebitmap", "createImageBitmap")}}{{Spec2('HTML WHATWG')}} 
- -

Compatibilidad con navegadores

- - - -

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

- -

Ver también

- -
    -
  • {{domxref("CanvasRenderingContext2D.drawImage()")}}
  • -
  • {{domxref("ImageData")}}
  • -
diff --git a/files/es/web/api/windoworworkerglobalscope/fetch/index.html b/files/es/web/api/windoworworkerglobalscope/fetch/index.html deleted file mode 100644 index 9540fe5d05..0000000000 --- a/files/es/web/api/windoworworkerglobalscope/fetch/index.html +++ /dev/null @@ -1,177 +0,0 @@ ---- -title: WindowOrWorkerGlobalScope.fetch() -slug: Web/API/WindowOrWorkerGlobalScope/fetch -tags: - - API - - Experimental - - Fetch - - Fetch API - - GlobalFetch - - Petición - - Referencia - - metodo - - solicitud -translation_of: Web/API/WindowOrWorkerGlobalScope/fetch ---- -
{{APIRef("Fetch API")}}
- -

El método fetch() del mixin {{domxref("WindowOrWorkerGlobalScope")}} lanza el proceso de solicitud de un recurso de la red. Esto devuelve una promesa que resuelve al objeto {{domxref("Response")}} que representa la respuesta a la solicitud realizada.

- -

Tanto {{domxref("Window")}} como {{domxref("WorkerGlobalScope")}} implementan WorkerOrGlobalScope, por lo que el método fetch() está disponible en prácticamente cualquier contexto desde el que se pueda necesitar solicitar un recurso.

- -

Una promesa {{domxref("WindowOrWorkerGlobalScope.fetch","fetch()")}} se rechaza con un {{jsxref("TypeError")}} cuando sucede un error en la red, aunque normalmente significa un tema de permisos o similar. Una comprobación más precisa de una solicitud con fetch() debería comprobar que la promesa se resuelve, y que la propiedad {{domxref("Response.ok")}} tiene valor true. Un estatus HTTP 404 no constituye un error de red.

- -

El método fetch() es controlado por la directiva connect-src de la Política de Seguridad de Contenido (Content Security Policy) en lugar de la directiva del recurso que se solicita.

- -
-

Nota: Los parámetros del método fetch() son indénticos a los del constructor de {{domxref("Request.Request","Request()")}}.

-
- -

Sintaxis

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

Parámetros

- -
-
input
-
Define el recurso que se quiere solicitar. Puede ser: -
    -
  • Un {{domxref("USVString")}} con la URL del recurso a solicitar. Algunos navegadores aceptan los esquemas blob: y data:.
  • -
  • Un objeto {{domxref("Request")}}.
  • -
-
-
init {{optional_inline}}
-
Objeto de opciones que contiene configuraciones para personalizar la solicitud. Estas opciones pueden ser: -
    -
  • method: El método de solicitud, p.ej., GET, POST.
  • -
  • headers: Cualquier cabecera que se quiera añadir a la solicitud, contenidas en un objeto {{domxref("Headers")}} o un objeto literal con valores {{domxref("ByteString")}}.
  • -
  • body: Cualquier cuerpo que se quiera añadir a la solicitud: puede ser un {{domxref("Blob")}}, {{domxref("BufferSource")}}, {{domxref("FormData")}}, {{domxref("URLSearchParams")}}, u objeto {{domxref("USVString")}}. Nótese que las solicitudes con métodos GETHEAD no pueden tener cuerpo.
  • -
  • mode: El modo a usar en la solicitud, p.ej., cors, no-cors, o same-origin.
  • -
  • credentials: Las credenciales que se quieran utilizar para la solicitud: omit, same-origin, o include. Para enviar automáticamente las cookies del dominio actual, debe indicarse esta opción. Desde Chrome 50, esta propiedad también acepta una instancia de {{domxref("FederatedCredential")}} o de {{domxref("PasswordCredential")}}.
  • -
  • cache: El modo de caché a utilizar en la solicitud: default, no-store, reload, no-cache, force-cache, o only-if-cached.
  • -
  • redirect: El modo de redirección a usar: follow (seguir redirecciones automáticamente), error (abortar si sucede un error durante la redirección), o manual (gestionar redirecciones manualmente). El valor por defecto en Chrome es follow (hasta la versión 46 era manual).
  • -
  • referrer: Un {{domxref("USVString")}} que especifique no-referrerclient, o una URL. El valor por defecto es client.
  • -
  • referrerPolicy: Especifica el valor de la cabecera HTTP referer. Puede ser no-referrer, no-referrer-when-downgrade, origin, origin-when-cross-origin, unsafe-url.
  • -
  • integrity: Contiene el valor de integridad de subrecurso (subresource integrity) de la solicitud (p.ej., sha256-BpfBw7ivV8q2jLiT13fxDYAe2tJllusRSZ273h2nFSE=).
  • -
  • keepalive: La opción keepalive se puede usar para permitir que recurso dure más que la página. Las solicitudes con el indicador keepalive son un reemplazo de la API {{domxref("Navigator.sendBeacon()")}}. 
  • -
  • signal: Una instancia de objeto {{domxref("AbortSignal")}}; permite comunicarse con con una solicitud vigente y abortarla si se desea via {{domxref("AbortController")}}.
  • -
-
-
- -

Return value

- -

Una {{domxref("Promise")}} que resuelve a un objeto {{domxref("Response")}}.

- -

Excepciones

- - - - - - - - - - - - - - - - - - -
TipoDescriptción
AbortErrorSe abortó la solicitud (mediante {{domxref("AbortController.abort()")}}).
TypeErrorDesde Firefox 43, fetch() lanza un TypeError si la URL tiene credenciales, como en http://usuario:clave@ejemplo.com.
- -

Ejemplo

- -

En el ejemplo de solicitud con Request (ver Fetch Request live) creamos un nuevo objeto {{domxref("Request")}} usando el constructor pertinente, y realizamos una solicitud usando fetch(). Dado que estamos solicitando una imagen, ejecutamos {{domxref("Body.blob()")}} en la respuesta para darle el tipo MIME correspondiente para que sea gestionada apropiadamente, luego creamos un objeto URL de ella para mostrarla en un elemento {{htmlelement("img")}}.

- -
var miImagen = document.querySelector('img');
-
-var miSolicitud = new Request('flores.jpg');
-
-fetch(miSolicitud).then(function(respuesta) {
-  return respuesta.blob();
-}).then(function(respuesta) {
-  var objeto = URL.createObjectURL(respuesta);
-  miImagen.src = objeto;
-});
- -

En el ejemplo de solicitud con inicializador y Request (ver Fetch Request init live) hacemos lo mismo pero además pasamos un objeto inicializador cuando invocamos el fetch():

- -
var miImagen = document.querySelector('img');
-
-var misCabeceras = new Headers();
-misCabeceras.append('Content-Type', 'image/jpeg');
-
-var miInicializador = { method: 'GET',
-                        headers: misCabeceras,
-                        mode: 'cors',
-                        cache: 'default' };
-
-var miSolicitud = new Request('flores.jpg');
-
-fetch(miSolicitud,miInicializador).then(function(respuesta) {
-  ...
-});
- -

Nótese que también podríamos pasar el objeto inicializador con el constructor de Request para conseguir el mismo efecto, p.ej.:

- -
var miSolicitud = new Request('flores.jpg', miInicializador);
- -

También se puede usar un objeto literal a modo de headers en init.

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

Especificaciones

- - - - - - - - - - - - - - - - - - - - - - - - -
EspecificaciónEstadoComentarios
{{SpecName('Fetch','#fetch-method','fetch()')}}{{Spec2('Fetch')}}Definida parcialmente en WindowOrWorkerGlobalScope en la especificación más reciente.
{{SpecName('Fetch','#dom-global-fetch','fetch()')}}{{Spec2('Fetch')}}Definición inicial
{{SpecName('Credential Management')}}{{Spec2('Credential Management')}}Añade una instancia de {{domxref("FederatedCredential")}} o {{domxref("PasswordCredential")}} como valor posible para init.credentials.
- -

Compatibilidad con navegadores

- - - -

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

- -

Ver también

- - diff --git a/files/es/web/api/windoworworkerglobalscope/indexeddb/index.html b/files/es/web/api/windoworworkerglobalscope/indexeddb/index.html deleted file mode 100644 index e6ef3fe5cd..0000000000 --- a/files/es/web/api/windoworworkerglobalscope/indexeddb/index.html +++ /dev/null @@ -1,141 +0,0 @@ ---- -title: WindowOrWorkerGlobalScope.indexedDB -slug: Web/API/WindowOrWorkerGlobalScope/indexedDB -translation_of: Web/API/WindowOrWorkerGlobalScope/indexedDB ---- -

{{ APIRef() }}

- -

La propiedad indexedDB del mixin {{domxref("WindowOrWorkerGlobalScope")}} proporciona un mecanismo para que las aplicaciones puedan acceder asíncronamente a las capacidades de las bases de datos indexadas.

- -

Sintaxis

- -
var DBOpenRequest = self.indexedDB.open('toDoList');
- -

Valor

- -

Un objeto {{domxref("IDBFactory")}}.

- -

Ejemplo

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

Especificaciones

- - - - - - - - - - - - - - - - - - - -
EspecificaciónEstadoComentario
{{SpecName('IndexedDB 2', '#dom-windoworworkerglobalscope-indexeddb', 'indexedDB')}}{{Spec2('IndexedDB 2')}}Definido en un WindowOrWorkerGlobalScope parcial en la última especificación.
{{SpecName('IndexedDB', '#widl-IDBEnvironment-indexedDB', 'indexedDB')}}{{Spec2('IndexedDB')}}Definición inicial.
- -

Compatibilidad de Navegadores

- -
{{CompatibilityTable}}
- -
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
CaracterísticaChromeEdgeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Soporte básico23{{property_prefix("webkit")}}
- 24
{{CompatVersionUnknown}}10 {{property_prefix("moz")}}
- {{CompatGeckoDesktop("16.0")}}
- {{CompatGeckoDesktop("52.0")}}[1]
10, parcial157.1
Disponible en los workers{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatGeckoMobile("37.0")}}{{CompatUnknown}}{{CompatVersionUnknown}}{{CompatUnknown}}
-
- -
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
CaracterísticaAndroidEdgeFirefox Mobile (Gecko)Firefox OSIE PhoneOpera MobileSafari Mobile
Soporte básico4.4{{CompatVersionUnknown}}{{CompatGeckoMobile("22.0")}}
- {{CompatGeckoMobile("52.0")}}[1]
1.0.110228
Disponible en los workers{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatGeckoMobile("37.0")}}{{CompatVersionUnknown}}{{CompatUnknown}}{{CompatVersionUnknown}}{{CompatUnknown}}
-
- -

[1] indexedDB se define ahora en el mixin {{domxref("WindowOrWorkerGlobalScope")}}.

- -

Ver también

- -
    -
  • Utilización de IndexedDB
  • -
  • Iniciando transacciones: {{domxref("IDBDatabase")}}
  • -
  • Usando transacciones: {{domxref("IDBTransaction")}}
  • -
  • Estableciendo un rango de claves: {{domxref("IDBKeyRange")}}
  • -
  • Recuperación y edición de tus datos: {{domxref("IDBObjectStore")}}
  • -
  • Utilización de cursores: {{domxref("IDBCursor")}}
  • -
  • Ejemplo de referencia: To-do Notifications (ver ejemplo live.)
  • -
diff --git a/files/es/web/api/windoworworkerglobalscope/issecurecontext/index.html b/files/es/web/api/windoworworkerglobalscope/issecurecontext/index.html deleted file mode 100644 index a99c499c7c..0000000000 --- a/files/es/web/api/windoworworkerglobalscope/issecurecontext/index.html +++ /dev/null @@ -1,86 +0,0 @@ ---- -title: WindowOrWorkerGlobalScope.isSecureContext -slug: Web/API/WindowOrWorkerGlobalScope/isSecureContext -translation_of: Web/API/WindowOrWorkerGlobalScope/isSecureContext ---- -

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

- -

La propiedad de sólo-lectura isSecureContext, de la interface  {{domxref("WindowOrWorkerGlobalScope")}} Devuelve un booleano indicando si el contexto actual es seguro (true) or not (false).

- -

Sintaxis

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

Valor

- -

Un {{domxref("Boolean")}}.

- -

Especificaciones

- - - - - - - - - - - - - - -
EspecificaciónEstadoComentario
{{SpecName('Secure Contexts', 'webappapis.html#dom-origin', 'WindowOrWorkerGlobalScope.isSecureContext')}}{{Spec2('Secure Contexts')}}Definición inicial.
- -

Compatibilidad de Navegadores

- -

{{CompatibilityTable}}

- -
- - - - - - - - - - - - - - - - - - - -
CaracterísticaChromeFirefox (Gecko)Internet ExplorerOperaSafari
Soporte básico{{CompatChrome(55)}}{{CompatGeckoDesktop(52)}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
-
- -
- - - - - - - - - - - - - - - - - - - - - -
CaracterísticaAndroid WebviewChrome para AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Soporte básico{{CompatChrome(55)}}{{CompatChrome(55)}}{{CompatGeckoMobile(52)}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
-
diff --git a/files/es/web/api/windoworworkerglobalscope/setinterval/index.html b/files/es/web/api/windoworworkerglobalscope/setinterval/index.html deleted file mode 100644 index a00e4b2c93..0000000000 --- a/files/es/web/api/windoworworkerglobalscope/setinterval/index.html +++ /dev/null @@ -1,693 +0,0 @@ ---- -title: WindowTimers.setInterval() -slug: Web/API/WindowOrWorkerGlobalScope/setInterval -tags: - - API - - DOM - - Gecko - - Intervalos - - Method - - Temporizadores - - Temporizadores de JavaScript - - WindowTimers - - setInterval -translation_of: Web/API/WindowOrWorkerGlobalScope/setInterval -original_slug: Web/API/WindowTimers/setInterval ---- -
{{APIRef("HTML DOM")}}
- -
Ejecuta una función o un fragmento de código de forma repetitiva cada vez que termina el periodo de tiempo determinado. Devuelve un ID de proceso.
- -
- -

Sintaxis

- -
var procesoID = window.setInterval(función, intervaloDeTiempo[, parámetro1, parámetro2, ... , parámetroN]);
-var procesoID = window.setInterval(código, intervaloDeTiempo);
-
- -

Parámetros

- -
-
función
-
La {{jsxref("function")}} que será ejecutada cada intervaloDeTiempo milisegundos.
-
código
-
Una sintaxis opcional permite introducir una cadena en lugar de una función, la cual es evaluada y ejecutada cada intervaloDeTiempo milisegundos. Se recomienda evitar esta sintaxis por la misma razón por la que el comando {{jsxref("eval", "eval()")}} conlleva problemas de seguridad.
-
intervaloDeTiempo
-
El tiempo en milisegundos (1/1000 de segundo, ms) que se debe esperar entre cada ejecución de la función o del código. Si el valor es menor que 10, se usará 10 en su lugar. El tiempo entre cada ejecución puede ser mayor al que indicamos, para mayor información puedes revisar el siguiente artículo: {{SectionOnPage("/en-US/docs/Web/API/WindowTimers/setTimeout", "Reasons for delays longer than specified")}}.
-
-
El parámetro intervaloDeTiempo es convertido en un entero de 32 bits con signo en el IDL, por lo que el valor más grande que puede tener es 2,147,483,647 milisegundos, aproximadamente 24.8 días.
-
-
parámetro1, ..., parámetroN {{optional_inline}}
-
Parámetros adicionales que se pasan a la función a ejecutar.
-
- -
-

En Internet Explorer 9 y anteriores no es posible pasar más parámetros mediante esta sintaxis. Si quieres activar esta funcionalidad en dichos navegadores deberás usar un polyfill (entra en la sección Callback arguments).

-
- -

Valor de Retorno

- -

El valor de retorno procesoID es un valor numérico distinto de cero que identifica al temporizador que fue creado al llamar setInterval(); este valor puede ser usado como parámetro en la función {{domxref("Window.clearInterval()")}} para detener el temporizador. Las funciones setInterval() y {{domxref("WindowTimers.setTimeout", "setTimeout()")}} comparten la misma pila de IDs, por lo que, técnicamente, los comandos clearInterval() y {{domxref("WindowTimers.clearTimeout", "clearTimeout()")}} pueden usarse indiscriminadamente. Sin embargo, por motivos de claridad y mantenimiento, es importante usarlos como corresponde.

- -
-

Nota: El argumento intervaloDeTiempo se convierte aun entero con signo de 32 bits. Esto limita efectivamente al intervaloDeTiempo a valores de 2147483647 ms, ya que se especifica como entero con signo en el IDL.

-
- -

Ejemplos

- -

Ejemplo 1: Sintaxis básica

- -

El siguiente ejemplo muestra la sintaxis básica.

- -
var intervalID = window.setInterval(miFuncion, 500, 'Parametro 1', 'Parametro 2');
-
-function miFuncion(a,b) {
-  // Aquí va tu código
-  // Los parámetros son opcionales completamente
-  console.log(a);
-  console.log(b);
-}
-
- -

Ejemplo 2: Alternando dos colores

- -

El siguiente ejemplo se llama a la función flashtext() una vez por segundo hasta que se presiona el botón Detener.

- -
<!DOCTYPE html>
-<html>
-<head>
-  <meta charset="UTF-8" />
-  <title>Ejemplo de setInterval/clearInterval</title>
-  <script>
-     var nIntervId;
-
-     function cambiaDeColor() {
-        nIntervId = setInterval(flasheaTexto, 1000);
-     }
-
-     function flasheaTexto() {
-        var oElem = document.getElementById('mi_mensaje');
-        oElem.style.color = oElem.style.color == 'red' ? 'blue' : 'red';
-        //oElem.style.color ... es un operador ternario o condicional
-     }
-
-     function detenerCambioDeColor() {
-        clearInterval(nIntervId);
-     }
-  </script>
-</head>
-<body onload="cambiaDeColor();">
-  <div id="mi_mensaje">
-    <p>¡Hola mundo!</p>
-  </div>
-  <button onclick="detenerCambioDeColor();">Detener</button>
-</body>
-</html>
-
- -

Ejemplo 3: Simulando una máquina de escribir

- -

El siguiente ejemplo simula una máquina de escribir, primero borra el contenido de una lista de nodos (NodeList) que coinciden con un grupo de selectores y después lo escribe lentamente.

- -
<!DOCTYPE html>
-<html>
-<head>
-<meta charset="UTF-8" />
-<title>Máquina de Escribir con JavaScript</title>
-<script>
-  function maquinaEscribir (sSelector, nRate) {
-
-      function limpiar () {
-        clearInterval(nIntervId);
-        bTyping = false;
-        bStart = true;
-        oCurrent = null;
-        aSheets.length = nIdx = 0;
-      }
-
-      function desplazarse (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]];
-
-          desplazarse(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 mecanografear () {
-        if (sPart.length === 0 && desplazarse(aSheets[nIdx], 0, true) && nIdx++ === aSheets.length - 1) { limpiar(); return; }
-
-        oCurrent.nodeValue += sPart.charAt(0);
-        sPart = sPart.slice(1);
-      }
-
-      function Hoja (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 Hoja(this.parts[nChild]);
-        }
-      }
-
-      var
-        nIntervId, oCurrent = null, bTyping = false, bStart = true,
-        nIdx = 0, sPart = "", aSheets = [], aMap = [];
-
-      this.rate = nRate || 100;
-
-      this.ejecuta = 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 Hoja(aItems[nItem]));
-            /* Uncomment the following line if you have previously hidden your elements via CSS: */
-            // aItems[nItem].style.visibility = "visible";
-          }
-
-          bStart = false;
-        }
-
-        nIntervId = setInterval(mecanografear, this.rate);
-        bTyping = true;
-      };
-
-      this.pausa = function () {
-        clearInterval(nIntervId);
-        bTyping = false;
-      };
-
-      this.finaliza = function () {
-        oCurrent.nodeValue += sPart;
-        sPart = "";
-        for (nIdx; nIdx < aSheets.length; desplazarse(aSheets[nIdx++], 0, false));
-        limpiar();
-      };
-  }
-
-    /* usage: */
-    var oTWExample1 = new maquinaEscribir(/* elements: */ "#article, h1, #info, #copyleft", /* frame rate (optional): */ 15);
-
-    /* default frame rate is 100: */
-    var oTWExample2 = new maquinaEscribir("#controls");
-
-    /* you can also change the frame rate value modifying the "rate" property; for example: */
-    // oTWExample2.rate = 150;
-
-    onload = function () {
-      oTWExample1.ejecuta();
-      oTWExample2.ejecuta();
-    };
-</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.ejecuta();">Ejecutar</span> | <span class="intLink" onclick="oTWExample1.pausa();">Pausar</span> | <span class="intLink" onclick="oTWExample1.finaliza();">Terminar</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>Maquina de Escribir en JavaScript </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>
-
- -

Observa este ejemplo en acción. Ver más: clearInterval().

- -

Argumentos de Callback

- -

Como se mencionó previamente Internet Explorer version 9 y anteriores no soportan el pasar argumentos a la función Callback en setTimeout() ni en setInterval(). El siguiente código específico de Internet Explorer muestra un método de superar esta limitante. Para usarlo basta añadir el código marcado al inicio de tu script.

- -
/*\
-|*|
-|*|  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;
-}
-
- -

Otra posible solución es el usar funciones anónimas para llamar al Callback, aunque esta solución es un poco más cara. Ejemplo:

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

También puedes hacer uso de function's bind. Ejemplo:

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

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

- -

A partir de Gecko 5.0 {{geckoRelease("5.0")}}, los intervalos no se disparan más de una vez por segundo en las pestañas inactivas.

- -

Problemas usando "this"

- -

Cuando pasas el método de un objeto a la función setInterval() éste es invocado fuera de su contexto. Esto puede crear un valor de this que puede no ser el esperado. Este problema es abordado en detalle en JavaScript reference.

- -

Explicación

- -

Cuando setInterval() o setTimeOut() ejecuta un determinado código o función, ésta corre en un contexto de ejecución separado al de la función en la que se creó dicho temporizador. Por esta razón a la palabra clave this se le asigna el valor del objeto window (o el objeto global), no es igual que usar this dentro de una fuinción que invoque a setTimeOut(). Observa el siguiente ejemplo (que utiliza setTimeOut() en lugar de setInterval() – el problema, de hecho, es el mismo para ambos temporizadores):

- -
miArreglo = ["cero", "uno", "dos"];
-
-miArreglo.miMetodo = function (sPropiedad) {
-    alert(arguments.length > 0 ? this[sPropiedad] : this);
-};
-
-miArreglo.miMetodo(); // imprime "cero,uno,dos"
-miArreglo.miMetodo(1); // imprime "uno"
-setTimeout(miArreglo.miMetodo, 1000); // imprime "[object Window]" despues de 1 segundo
-setTimeout(miArreglo.miMetodo, 1500, "1"); // imprime "undefined" despues de 1,5 segundos
-// tratemos de pasar el objeto 'this'
-setTimeout.call(miArreglo, miArreglo.miMetodo, 2000); // error: "NS_ERROR_XPC_BAD_OP_ON_WN_PROTO: Illegal operation on WrappedNative prototype object"
-setTimeout.call(miArreglo, miArreglo.miMetodo, 2500, 2); // same error
- -

Como puedes ver no hay forma de pasar el objeto this a la función de Callback en la versión anterior de JavaScript.

- -

Una posible solución

- -

Una posible alternativa para resolver ésto es reemplazar las dos funciones globales nativas setTimeout() y setInterval() con las siguientes funciones no nativas que permiten su ejecución a través del método Function.prototype.call. El siguiente ejemplo muestra una posible sustitución:

- -
// Permite el pase del objeto 'this' a través de temporizadores JavaScript
-
-var __nativeST__ = window.setTimeout, __nativeSI__ = window.setInterval;
-
-window.setTimeout = function (vCallback, nDelay /*, argumentoAPasar1, argumentuAPasar2, 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 /*, argumentoAPasar1, argumentoAPasar2, etc. */) {
-  var oThis = this, aArgs = Array.prototype.slice.call(arguments, 2);
-  return __nativeSI__(vCallback instanceof Function ? function () {
-    vCallback.apply(oThis, aArgs);
-  } : vCallback, nDelay);
-};
-
- -
Estos dos reemplazos también permiten el camino estándar en HTML5 de pasar argumentos arbitrarios a las funciones de Callback de los temporizadores dentro de IE. Por lo tanto, pueden utilizarse como rellenos (polyfills) no estándar. Para más información vea callback arguments paragraph.
- -

Prueba de nueva funcionalidad:

- -
miArreglo = ["cero", "uno", "dos"];
-
-miArreglo.miMetodo = function (sProperty) {
-    alert(arguments.length > 0 ? this[sProperty] : this);
-};
-
-setTimeout(alert, 1500, "Hola Mundo!"); // la utilizacion estandar de setTimeout y de setInterval se mantiene, pero...
-setTimeout.call(miArreglo, miArreglo.miMetodo, 2000); // imprime "cero,uno,dos" despues de 2 segundos
-setTimeout.call(miArreglo, miArreglo.miMetodo, 2500, 2); // imprime "dos" despues de 2,5 segundos
-
- -

Otra solución más compleja está en la siguiente liga de framework.

- -
JavaScript 1.8.5 introduce el método Function.prototype.bind(), el cual permite especificar el valor de this para todas sus llamadas en una determinada función. Esto permite sobrellevar facilmente diferentes problemas de contexto con el uso de la palabra this. También, ES2015 soporta arrow functions, dentro del lenguaje nos permite escribir cosas como setInterval( () => this.myMethod) si estamos dentro del método de miArreglo .
- -

MiniDaemon - Un framework para administrar temporizadores

- -

En proyectos que requieren muchos temporizadores puede volverse complicado el seguimiento de todos los eventos generados. Una forma de facilitar la administración de timers es guardando sus estados en un objeto. El siguiente ejemplo muestra este tipo de abstracción, la arquitectura del constructor evita explicitamente el uso de cerraduras. También ofrece un camino alternativo para pasar el objeto this a la función de Callback (observa la sección Problemas usando "this" para más detalles). Puedes consultar también el siguiente código en GitHub.

- -
Para una versión más modular de este (Daemon)puedes verlo en JavaScript Daemons Management. Aquí encontrarás una versión mas complicada que se reduce a una colección escalable de métodos para el constructor Daemon. Éste constructor no es más que un clon del  MiniDaemon con soporte para las funciones init y onstart declarables durante la instanciación del mismo. Por esto el MiniDaemon framework se mantiene como el camino recomendado para realizar animaciones simples.
- -

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 pasa argumentos a la función callback. Si quieres trabajar con ellos en navegadores que no soportan nativamente esta característica, usa uno de los métodos propuestos arriba.
- -

Sintaxis

- -

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

- -

Descripción

- -

Regresa un Objecto que contiene la información necesaria para una animación (como el objeto this, la función de Callback, la duración y el frame-rate).

- -

Parámetros

- -
-
thisObject
-
El valor de la palabra this sobre el cual funcionará la función de Callback. Puede ser un objecto o null.
-
callback
-
La función que se invocará repetidas veces. Dicha función se invocará con tres parámetros: index que corresponde al valor iterativo de cada invocación, length que es el número total de invocaciones asignadas al daemon (puede ser un valor finito o Infinity) y backwards (valor booleano que expresa cuando el valor de index es creciente o decreciente). Es similar a callback.call(thisObject, index, length, backwards). Si la función de Callback regresa un valor false el deamon se detiene.
-
rate (optional)
-
El tiempo minimo en milisegundos que transcurre entre cada invocación. El valor por omisión es 100.
-
length (optional)
-
El número total de invocaciones. Puede ser un valor entero positivo o Infinity. El valor por omisión es Infinity.
-
- -

Propiedades de la intancia MiniDaemon 

- -
-
myDaemon.owner
-
El objeto this sobre el cual se ejecuta el daemon (lectura/escritura). Puede ser un objecto o null.
-
myDaemon.task
-
La función que se invocará repetidas veces. Dicha función se invocará con tres parámetros: index que corresponde al valor iterativo de cada invocación, length que es el número total de invocaciones asignadas al daemon (puede ser un valor finito o Infinity) y backwards (valor booleano que expresa cuando el valor de index es creciente o decreciente). Es similar a callback.call(thisObject, index, length, backwards). Si la función de Callback regresa un valor false el deamon se detiene.
-
myDaemon.rate
-
El tiempo minimo en milisegundos que transcurre entre cada invocación. El valor por omición es 100 (lectura/escritura).
-
myDaemon.length
-
El número total de invocaciones. Puede ser un valor entero positivo o Infinity. El valor por omición es Infinity (lectura/escritura).
-
- -

MiniDaemon instances methods

- -
-
myDaemon.isAtEnd()
-
Regresa un valor boleano que expresa cuando el daemon está en posición de inicio/fin o no.
-
myDaemon.synchronize()
-
Sincroniza el tiempo de un deamon iniciado con el tiempo de su invocación.
-
myDaemon.pause()
-
Pausa el deamon.
-
myDaemon.start([reverse])
-
Inicia el daemon hacia adelante "forward" (el indice de cada invocación se incrementa) o hacia atrás "backwards" (el índice de cada invocación se decrementa).
-
- -

Métodos del objeto global del MiniDaemon

- -
-
MiniDaemon.forceCall(minidaemon)
-
Fuerza una sola función callback a la función minidaemon.task  en lugar del hecho de que se ha alcanzado el final o no. En cualquier caso la propiedad INDEX interna crece o decrece según la dirección del proceso.
-
- -

Ejemplo de uso

- -

Tu página 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>
- -

Prueba este ejemplo

- -

Notas

- -

La función setInterval() es usada frecuentemente para asignar una pausa para ejecutar funciones recurrentes, como por ejemplo pintar el siguiente cuadro de una animación.

- -

Puedes cancelar el ciclo iniciado por un setInterval() usando el comando window.clearInterval().

- -

Si solo deseas ejecutar el ciclo una sola vez despues de una pausa usa en su lugar la función window.setTimeout().

- -

Asegúrate que el tiempo de ejecución sea menor que la frecuencia

- -

Si existe la posibilidad de que tu función o el código a ejecutarse una y otra vez exeda el tiempo marcado en cada intervalo es recomendado que uses recursivamente el nombre de tu función usando window.setTimeout. Por ejemplo, si usas setInterval para hacer llamadas a un servidor remoto cada 5 segundos, la latencia en la red, un servidor que no responde, o cualquier otro tipo de contratiempo puede generar una pausa mayor a la que indicaste. De esta forma terminarás con solicitudes XHR apiladas que no se resolverán necesariamente en orden.

- -

En estos casos llamadas con un patrón de setTimeout() recursivo es preferible:

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

En este fragmento de código, la función loop() es declarada y es ejecutada inmediatamente. La función loop() es invocada de forma recursiva dentro de setTimeout() despues de cada ejecución. Si bien este patrón no garantiza una ejecución a intervalos fijos, si garantiza que nunca se ejecutará un paso sin que se haya finalizado el anterior. 

- -

Especificaciones

- - - - - - - - - - - - - - -
EspecificacionesEstatusComentarios
{{SpecName("HTML WHATWG", "webappapis.html#dom-setinterval", "WindowTimers.setInterval()")}}{{Spec2("HTML WHATWG")}}Definición inicial (DOM Level 0)
- -

Compatibilidad

- -
{{CompatibilityTable}}
- -
- - - - - - - - - - - - - - - - - - - - - - - - - - - -
CaracterísticaChromeFirefox (Gecko)[2]Internet ExplorerOperaSafari
Soporte básico1.0{{CompatGeckoDesktop("1")}}4.04.01.0
Soporta parámetros para callback[1]{{CompatVersionUnknown}}{{CompatVersionUnknown}}10.0{{CompatVersionUnknown}}{{CompatUnknown}}
-
- -
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
CaracterísticaAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Soporte básico1.01.0{{CompatGeckoMobile("1")}}6.06.01.0
Soporta parámetros para callback[1]{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
-
- -

[1] Whether it supports the optional parameters when in its first form or not.

- -

[2] Anterior a Firefox 13, Firefox pasaba un parametro adicional al callback, indicando el "actual lateness" del timeout en milisegundos. Este parámetro no estandar dejó de usarse en versiones posteriores a Firefox 13. No es recomendable que extensiones basadas en XPCOM para Firefox usen setInterval(), ya que las actualizaciones pueden causar el que el objeto {{domxref("Window")}} se actualice perdiendo los temporizadores. Deberás usar en su lugar {{interface("nsITimer")}}.

- -

Ver más

- -
    -
  • JavaScript timers
  • -
  • {{domxref("WindowTimers.setTimeout")}}
  • -
  • {{domxref("WindowTimers.clearTimeout")}}
  • -
  • {{domxref("WindowTimers.clearInterval")}}
  • -
  • {{domxref("window.requestAnimationFrame")}}
  • -
  • Daemons management
  • -
diff --git a/files/es/web/api/windoworworkerglobalscope/settimeout/index.html b/files/es/web/api/windoworworkerglobalscope/settimeout/index.html deleted file mode 100644 index 7b15ffa392..0000000000 --- a/files/es/web/api/windoworworkerglobalscope/settimeout/index.html +++ /dev/null @@ -1,341 +0,0 @@ ---- -title: WindowOrWorkerGlobalScope.setTimeout -slug: Web/API/WindowOrWorkerGlobalScope/setTimeout -tags: - - API - - HTML DOM - - WindowOrWorkerGlobalScope - - setTimeout -translation_of: Web/API/WindowOrWorkerGlobalScope/setTimeout -original_slug: Web/API/WindowTimers/setTimeout ---- -
{{APIRef("HTML DOM")}}
- -

El método setTimeout() del mixin {{domxref("WindowOrWorkerGlobalScope")}} establece un temporizador que ejecuta una función o una porción de código después de que transcurre un tiempo establecido.

- - -

Sintaxis

- -
var idTemporizador = scope.setTimeout(funcion[, retraso, parametro1, parametro2, ...]);
-var idTimeout = scope.setTimeout(funcion[, retraso]);
-var idTimeout = scope.setTimeout(codigo[, retraso]);
-
- -

Parámetros

- -
-
funcion
-
Una {{jsxref("function")}} para ejecutar después de que expire el temporizador.
-
codigo
-
Una sintaxis opcional que le permite incluir una cadena en lugar de una función, la cual es compilada y ejecutada cuando el temporizador expira. Esta sintaxis no se recomienda por las mismas razones que hacen del uso de {{jsxref("Global_Objects/eval", "eval()")}} un riesgo de seguridad.
-
retraso {{optional_inline}}
-
Tiempo, en milisegundos  (milésimas de segundo), que el temporizador debe esperar antes de ejecutar la función o el código. Si se omite este parámetro se usa el valor 0. Tenga en cuenta que el retraso real puede ser más prolongado; ver más abajo {{anch("Reasons for delays longer than specified")}}.
-
param1, ..., paramN {{optional_inline}}
-
Parámetros adicionales que se pasan a la función especificada por  func una vez el temporizador expira.
-
- -
Nota: Pasar parámetros adicionales a la función en la primera sintaxis no funciona en Internet Explorer 9 o inferior. Si quiere habilitar esta funcionalidad en ese navegador,  debe usar un código de compatibilidad (vea la sección Callback arguments).
- -

Valor retornado

- -

El valor retornado IDtemporizador es númerico y no es cero; identifica el temporizador creado con la llamada a setTimeout(); este valor puede pasarse a {{domxref("WindowOrWorkerGlobalScope.clearTimeout()")}} para cancelar el temporizador.

- -

Puede ser útil advertir que  setTimeout() y {{domxref("WindowOrWorkerGlobalScope.setInterval", "setInterval()")}} comparten la misma piscina de IDs, y que tanto clearTimeout() como {{domxref("WindowOrWorkerGlobalScope.clearInterval", "clearInterval()")}} pueden intercambiarse.  Por claridad, sin embargo,  debe hacerlos coincidir para evitar confusiones cuando mantenga su código.

- -

Ejemplo

- -

El siguiente ejemplo establece dos botenes simples en una página web y los engancha a las rutinas setTimeout() y clearTimeout(). Presionando el primer botón establecerá un temporizador que llama un diálogo de alerta después de dos segundos y guarda el id del temporizador para usarlo con clearTimeout(). Opcionalmente puede cancelar este temporizador presionando el segundo botón.

- -

Contenido HTML

- -
<p>Ejemplo funcional</p>
-<button onclick="delayedAlert();">Muestra una caja de alerta después de dos segundos</button>
-<p></p>
-<button onclick="clearAlert();">Cancela la alerta antes de que ocurra</button>
-
- -

Contenido JavaScript

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

{{ EmbedLiveSample('Example') }}

- -

Vea también clearTimeout() example.

- -

Callback arguments

- -

Si necesita pasar un argumento a su función callback, pero necesita que funcione en Internet Explorer, que no soporta el envío de parámetros adicionales (ni con setTimeout()setInterval()) usted puede incluir este código de compatibilidad IE-specific que habilitará la funcionalidad estándar de HTML5 para pasar los parámetros adicionales en ese navegador para ambos temporizadores solamente insertandolo al inicio de sus scripts.

- -
/*\
-|*|
-|*|  IE-specific polyfill which enables the passage of arbitrary arguments to the
-|*|  callback functions of JavaScript timers (HTML5 standard syntax).
-|*|
-|*|  https://developer.mozilla.org/en-US/docs/DOM/window.setInterval
-|*|
-|*|  Syntax:
-|*|  var timeoutID = window.setTimeout(func, delay, [param1, param2, ...]);
-|*|  var timeoutID = window.setTimeout(code, delay);
-|*|  var intervalID = window.setInterval(func, delay[, param1, param2, ...]);
-|*|  var intervalID = window.setInterval(code, delay);
-|*|
-\*/
-
-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;
-}
-
- -

Arreglo solo para IE

- -

Si quiere una solución completamente no intrusiva con otros navegadores móviles o de escritorio, incluyendo IE 9 y superior, puede usar los comentarios condicionales de JavaScript:

- -
/*@cc_on
-  // conditional IE < 9 only fix
-  @if (@_jscript_version <= 6)
-  (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.apply(this,a)},t)}});
-  @end
-@*/
-
- -

O usar un enfoque más limpio basado en el condicional para IE de HTML:

- -
<!--[if lt 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.apply(this,a)},t)}
-});
-</script><![endif]-->
-
- -

Otra posibilidad es usar una función anónima para llamar el callback, pero esta solución es un poco más costosa. Ejemplo:

- -
var intervalID = setTimeout(function() { myFunc("uno", "dos", "tres"); }, 1000);
-
- -

Sin embargo, otra posibilidad es usar function's bind. Ejemplo:

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

El problema "this"

- -

Cuando pasa un método a setTimeout() (o cualquier otra función , por el estilo), podría ser invocada con el valor de this equivocado. Este problema es explicado en detalle en la referencia de JavaScript.

- -

Explicación

- -

El código ejecutado por setTimeout() corre en un contexto de ejecución diferente al de la función por la que fue llamado. Como consecuencia, la palabra clave this para la función llamada será asignado al objeto window (o global); no tendrá el mismo valor del this de la función que llamó al setTimeout. Vea el siguiente ejemplo:

- -
myArray = ["cero", "uno", "dos"];
-myArray.myMethod = function (sProperty) {
-    alert(arguments.length > 0 ? this[sProperty] : this);
-};
-
-myArray.myMethod(); // imprime "cero,uno,dos"
-myArray.myMethod(1); // imprime "uno"
-setTimeout(myArray.myMethod, 1000); // imprime "[object Window]" después de 1 segundo
-setTimeout(myArray.myMethod, 1500, "1"); // imprime "undefined" después de 1.5 segundos
-// intentemos pasar el objeto 'this'
-setTimeout.call(myArray, myArray.myMethod, 2000); // error: "NS_ERROR_XPC_BAD_OP_ON_WN_PROTO: Illegal operation on WrappedNative prototype object"
-setTimeout.call(myArray, myArray.myMethod, 2500, 2); // mismo error
- -

Como puedes ver no hay forma de pasar el objeto this a la función callback.

- -

Una posible solución

- -

Una posible forma de resolver el problema del "this" es reemplazar las dos funciones globales nativas setTimeout() or setInterval()por dos no-nativas  que permitan su invocación a través del método Function.prototype.call. El siguiente ejemplo muestra un posible reemplazo:

- -
// 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);
-};
- -
Nota: Estos dos reemplazos habilitarán el estándar HTML5 para el paso de argumentos arbitrarios a las funciones callback de los temporizadores en IE. Pueden usarse como polyfills también. Vea el párrafo Callback arguments.
- -

Prueba de la nueva característica:

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

No hay soluciones nativas ad hoc a este problema.

- -
Nota: JavaScript 1.8.5 introduce el método Function.prototype.bind(, que permite especificar el valor que debería usarse como this para todas las llamadas a una función dada. Esto permite evitar fácilmente los problemas en los que no es claro que será, dependiendo del contexto desde el cual la función sea llamada.
- -

Notas

- -

Puede cancelar el temporizador usando window.clearTimeout(). Si desea tener una función llamada repetidamente (p.e., cada N milisegundos), considere usar window.setInterval().

- -

Es importante notar que la función o fragmento de código no puede ser ejecutado hasta que el hilo que llamó setTimeout()haya terminado.

- -

Pasando cadenas literales

- -

Pasando una cadena en vez de una función a setTimeout()pasa lo mismo que al usar eval.

- -
// Correcto
-window.setTimeout(function() {
-    alert("Hello World!");
-}, 500);
-
-// Incorrecto
-window.setTimeout("alert(\"Hello World!\");", 500);
-
-
- -

Las cadenas literales son evaluadas en el contexto global, así que los símbolos locales en el contexto donde setTimeout() fue llamado no estarán disponibles cuando la cadena es evaluada como código.

- -

Minimum/ maximum delay and timeout nesting

- -

Historically browsers implement setTimeout() "clamping": successive setTimeout() calls with delay smaller than the "minimum delay" limit are forced to use at least the minimum delay. The minimum delay, DOM_MIN_TIMEOUT_VALUE, is 4 ms (stored in a preference in Firefox: dom.min_timeout_value), with a DOM_CLAMP_TIMEOUT_NESTING_LEVEL of 5ms.

- -

In fact, 4ms is specified by the HTML5 spec and is consistent across browsers released in 2010 and onward. Prior to {{ geckoRelease("5.0") }}, the minimum timeout value for nested timeouts was 10 ms.

- -

In addition to "clamping", the timeout can also fire later when the page (or the OS/browser itself) is busy with other tasks.

- -

To implement a 0 ms timeout in a modern browser, you can use {{ domxref("window.postMessage()") }} as described here.

- -

Browsers including Internet Explorer, Chrome, Safari, and Firefox store the delay as a 32-bit signed Integer internally. This causes an Integer overflow when using delays larger than 2147483647, resulting in the timeout being executed immediately.

- -

Inactive tabs

- -

In {{ geckoRelease("5.0") }} and Chrome 11, timeouts are clamped to firing no more often than once per second (1000ms) in inactive tabs; see {{ bug(633421) }} for more information about this in Mozilla or crbug.com/66078 for details about this in Chrome.

- -

Compatibilidad de navegadores

- -

{{ CompatibilityTable() }}

- -
- - - - - - - - - - - - - - - - - - - - - - - - - - - -
CaracterísticaChromeFirefox (Gecko)Internet ExplorerOperaSafari
Soporte básico1.0{{ CompatGeckoDesktop("1") }}4.04.01.0
Soporta parámetros para callback*1{{ CompatVersionUnknown }}{{ CompatVersionUnknown }}10.0{{ CompatVersionUnknown }}{{ CompatUnknown }}
-
- -
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
CaracterísticaAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Soporte básico1.01.0{{ CompatGeckoMobile("1") }}6.06.01.0
Soporta parámetros para callback*1{{ CompatUnknown }}{{ CompatUnknown }}{{ CompatUnknown }}{{ CompatUnknown }}{{ CompatUnknown }}{{ CompatUnknown }}
-
- -

*1 Whether it supports the optional parameters when in its first form or not.

- -

Especificación

- -

Parte del DOM nivel 0, como se especifica en HTML5.

- -

Vea también

- - diff --git a/files/fr/_redirects.txt b/files/fr/_redirects.txt index 4524c14581..0e2dca875d 100644 --- a/files/fr/_redirects.txt +++ b/files/fr/_redirects.txt @@ -1006,9 +1006,9 @@ /fr/docs/DOM/window /fr/docs/Web/API/Window /fr/docs/DOM/window.URL.createObjectURL /fr/docs/Web/API/URL/createObjectURL /fr/docs/DOM/window.alert /fr/docs/Web/API/Window/alert -/fr/docs/DOM/window.atob /fr/docs/Web/API/WindowOrWorkerGlobalScope/atob -/fr/docs/DOM/window.btoa /fr/docs/Web/API/WindowOrWorkerGlobalScope/btoa -/fr/docs/DOM/window.clearInterval /fr/docs/Web/API/WindowOrWorkerGlobalScope/clearInterval +/fr/docs/DOM/window.atob /fr/docs/Web/API/atob +/fr/docs/DOM/window.btoa /fr/docs/Web/API/btoa +/fr/docs/DOM/window.clearInterval /fr/docs/Web/API/clearInterval /fr/docs/DOM/window.close /fr/docs/Web/API/Window/close /fr/docs/DOM/window.closed /fr/docs/Web/API/Window/closed /fr/docs/DOM/window.confirm /fr/docs/Web/API/Window/confirm @@ -1037,7 +1037,7 @@ /fr/docs/DOM/window.prompt /fr/docs/Web/API/Window/prompt /fr/docs/DOM/window.scroll /fr/docs/Web/API/Window/scroll /fr/docs/DOM/window.scrollTo /fr/docs/Web/API/Window/scrollTo -/fr/docs/DOM/window.setTimeout /fr/docs/Web/API/WindowOrWorkerGlobalScope/setTimeout +/fr/docs/DOM/window.setTimeout /fr/docs/Web/API/setTimeout /fr/docs/DOM/window.showModalDialog /fr/docs/Web/API/Window/showModalDialog /fr/docs/DOM:Autres_ressources /fr/docs/Web/API/Document_Object_Model /fr/docs/DOM:Selection:toString /fr/docs/Web/API/Selection/toString @@ -1158,9 +1158,9 @@ /fr/docs/DOM:table.caption /fr/docs/Web/API/HTMLTableElement/caption /fr/docs/DOM:window /fr/docs/Web/API/Window /fr/docs/DOM:window.alert /fr/docs/Web/API/Window/alert -/fr/docs/DOM:window.atob /fr/docs/Web/API/WindowOrWorkerGlobalScope/atob -/fr/docs/DOM:window.btoa /fr/docs/Web/API/WindowOrWorkerGlobalScope/btoa -/fr/docs/DOM:window.clearInterval /fr/docs/Web/API/WindowOrWorkerGlobalScope/clearInterval +/fr/docs/DOM:window.atob /fr/docs/Web/API/atob +/fr/docs/DOM:window.btoa /fr/docs/Web/API/btoa +/fr/docs/DOM:window.clearInterval /fr/docs/Web/API/clearInterval /fr/docs/DOM:window.close /fr/docs/Web/API/Window/close /fr/docs/DOM:window.closed /fr/docs/Web/API/Window/closed /fr/docs/DOM:window.confirm /fr/docs/Web/API/Window/confirm @@ -1182,7 +1182,7 @@ /fr/docs/DOM:window.parent /fr/docs/Web/API/Window/parent /fr/docs/DOM:window.prompt /fr/docs/Web/API/Window/prompt /fr/docs/DOM:window.scrollTo /fr/docs/Web/API/Window/scrollTo -/fr/docs/DOM:window.setTimeout /fr/docs/Web/API/WindowOrWorkerGlobalScope/setTimeout +/fr/docs/DOM:window.setTimeout /fr/docs/Web/API/setTimeout /fr/docs/DOM:window.showModalDialog /fr/docs/Web/API/Window/showModalDialog /fr/docs/DOMParser /fr/docs/Web/API/DOMParser /fr/docs/Dessin_de_texte_avec_canvas /fr/docs/Web/API/Canvas_API/Tutorial/Drawing_text @@ -3650,7 +3650,7 @@ /fr/docs/Web/API/FileReader/FileList /fr/docs/Web/API/FileList /fr/docs/Web/API/FormData/Utilisation_objets_FormData /fr/docs/Web/API/FormData/Using_FormData_Objects /fr/docs/Web/API/GlobalFetch /fr/docs/Web/API/WindowOrWorkerGlobalScope -/fr/docs/Web/API/GlobalFetch/fetch /fr/docs/Web/API/WindowOrWorkerGlobalScope/fetch +/fr/docs/Web/API/GlobalFetch/fetch /fr/docs/Web/API/fetch /fr/docs/Web/API/HTMLElement/dataset /fr/docs/orphaned/Web/API/HTMLOrForeignElement/dataset /fr/docs/Web/API/HTMLElement/focus /fr/docs/orphaned/Web/API/HTMLOrForeignElement/focus /fr/docs/Web/API/HTMLElement/style /fr/docs/orphaned/Web/API/ElementCSSInlineStyle/style @@ -3662,7 +3662,7 @@ /fr/docs/Web/API/HTMLOrForeignElement/tabIndex /fr/docs/orphaned/Web/API/HTMLOrForeignElement/tabIndex /fr/docs/Web/API/HTMLTableElement.caption /fr/docs/Web/API/HTMLTableElement/caption /fr/docs/Web/API/HTMLTableElement.insertRow /fr/docs/Web/API/HTMLTableElement/insertRow -/fr/docs/Web/API/IDBEnvironment/indexedDB /fr/docs/Web/API/WindowOrWorkerGlobalScope/indexedDB +/fr/docs/Web/API/IDBEnvironment/indexedDB /fr/docs/Web/API/indexedDB /fr/docs/Web/API/IDBRequest/blocked_event /fr/docs/Web/API/IDBOpenDBRequest/blocked_event /fr/docs/Web/API/IndexedDB_API/Basic_Concepts_Behind_IndexedDB /fr/docs/orphaned/Web/API/IndexedDB_API/Basic_Concepts_Behind_IndexedDB /fr/docs/Web/API/Location.assign /fr/docs/Web/API/Location/assign @@ -3756,9 +3756,9 @@ /fr/docs/Web/API/Web_Workers_API/Utilisation_des_web_workers /fr/docs/Web/API/Web_Workers_API/Using_web_workers /fr/docs/Web/API/Web_Workers_API/algorithme_clonage_structure /fr/docs/Web/API/Web_Workers_API/Structured_clone_algorithm /fr/docs/Web/API/Window.alert /fr/docs/Web/API/Window/alert -/fr/docs/Web/API/Window.atob /fr/docs/Web/API/WindowOrWorkerGlobalScope/atob -/fr/docs/Web/API/Window.btoa /fr/docs/Web/API/WindowOrWorkerGlobalScope/btoa -/fr/docs/Web/API/Window.clearInterval /fr/docs/Web/API/WindowOrWorkerGlobalScope/clearInterval +/fr/docs/Web/API/Window.atob /fr/docs/Web/API/atob +/fr/docs/Web/API/Window.btoa /fr/docs/Web/API/btoa +/fr/docs/Web/API/Window.clearInterval /fr/docs/Web/API/clearInterval /fr/docs/Web/API/Window.close /fr/docs/Web/API/Window/close /fr/docs/Web/API/Window.closed /fr/docs/Web/API/Window/closed /fr/docs/Web/API/Window.confirm /fr/docs/Web/API/Window/confirm @@ -3782,19 +3782,30 @@ /fr/docs/Web/API/Window.postMessage /fr/docs/Web/API/Window/postMessage /fr/docs/Web/API/Window.prompt /fr/docs/Web/API/Window/prompt /fr/docs/Web/API/Window.scrollTo /fr/docs/Web/API/Window/scrollTo -/fr/docs/Web/API/Window.setTimeout /fr/docs/Web/API/WindowOrWorkerGlobalScope/setTimeout +/fr/docs/Web/API/Window.setTimeout /fr/docs/Web/API/setTimeout /fr/docs/Web/API/Window.showModalDialog /fr/docs/Web/API/Window/showModalDialog /fr/docs/Web/API/Window/URL /fr/docs/conflicting/Web/API/URL -/fr/docs/Web/API/Window/caches /fr/docs/Web/API/WindowOrWorkerGlobalScope/caches +/fr/docs/Web/API/Window/caches /fr/docs/Web/API/caches /fr/docs/Web/API/Window/gamepaddisconnected /fr/docs/Web/API/Window/gamepaddisconnected_event /fr/docs/Web/API/Window/ondevicelight /fr/docs/orphaned/Web/API/Window/ondevicelight /fr/docs/Web/API/Window/onresize /fr/docs/conflicting/Web/API/GlobalEventHandlers/onresize /fr/docs/Web/API/WindowBase64 /fr/docs/Web/API/WindowOrWorkerGlobalScope /fr/docs/Web/API/WindowBase64/Décoder_encoder_en_base64 /fr/docs/Glossary/Base64 -/fr/docs/Web/API/WindowBase64/atob /fr/docs/Web/API/WindowOrWorkerGlobalScope/atob -/fr/docs/Web/API/WindowBase64/btoa /fr/docs/Web/API/WindowOrWorkerGlobalScope/btoa -/fr/docs/Web/API/WindowTimers/clearInterval /fr/docs/Web/API/WindowOrWorkerGlobalScope/clearInterval -/fr/docs/Web/API/WindowTimers/setTimeout /fr/docs/Web/API/WindowOrWorkerGlobalScope/setTimeout +/fr/docs/Web/API/WindowBase64/atob /fr/docs/Web/API/atob +/fr/docs/Web/API/WindowBase64/btoa /fr/docs/Web/API/btoa +/fr/docs/Web/API/WindowOrWorkerGlobalScope/atob /fr/docs/Web/API/atob +/fr/docs/Web/API/WindowOrWorkerGlobalScope/btoa /fr/docs/Web/API/btoa +/fr/docs/Web/API/WindowOrWorkerGlobalScope/caches /fr/docs/Web/API/caches +/fr/docs/Web/API/WindowOrWorkerGlobalScope/clearInterval /fr/docs/Web/API/clearInterval +/fr/docs/Web/API/WindowOrWorkerGlobalScope/crossOriginIsolated /fr/docs/Web/API/crossOriginIsolated +/fr/docs/Web/API/WindowOrWorkerGlobalScope/fetch /fr/docs/Web/API/fetch +/fr/docs/Web/API/WindowOrWorkerGlobalScope/indexedDB /fr/docs/Web/API/indexedDB +/fr/docs/Web/API/WindowOrWorkerGlobalScope/isSecureContext /fr/docs/Web/API/isSecureContext +/fr/docs/Web/API/WindowOrWorkerGlobalScope/origin /fr/docs/Web/API/origin +/fr/docs/Web/API/WindowOrWorkerGlobalScope/queueMicrotask /fr/docs/Web/API/queueMicrotask +/fr/docs/Web/API/WindowOrWorkerGlobalScope/setTimeout /fr/docs/Web/API/setTimeout +/fr/docs/Web/API/WindowTimers/clearInterval /fr/docs/Web/API/clearInterval +/fr/docs/Web/API/WindowTimers/setTimeout /fr/docs/Web/API/setTimeout /fr/docs/Web/API/Worker.Worker /fr/docs/Web/API/Worker/Worker /fr/docs/Web/API/Worker.onmessage /fr/docs/Web/API/Worker/onmessage /fr/docs/Web/API/Worker.postMessage /fr/docs/Web/API/Worker/postMessage diff --git a/files/fr/_wikihistory.json b/files/fr/_wikihistory.json index d71fb0691a..ccfb379d40 100644 --- a/files/fr/_wikihistory.json +++ b/files/fr/_wikihistory.json @@ -21577,112 +21577,6 @@ "Bzbarsky" ] }, - "Web/API/WindowOrWorkerGlobalScope/atob": { - "modified": "2019-09-24T09:32:03.862Z", - "contributors": [ - "NemoNobobyPersonne", - "tbroadley", - "fscholz", - "teoli", - "khalid32", - "Mgjbot", - "BenoitL", - "Celelibi" - ] - }, - "Web/API/WindowOrWorkerGlobalScope/btoa": { - "modified": "2019-03-18T21:13:03.287Z", - "contributors": [ - "PamProg", - "NemoNobobyPersonne", - "teoli", - "lovasoa", - "fscholz", - "jsx", - "e7d", - "Mgjbot", - "BenoitL", - "Celelibi" - ] - }, - "Web/API/WindowOrWorkerGlobalScope/caches": { - "modified": "2020-10-15T22:06:53.037Z", - "contributors": [ - "Arzak656", - "jonasgrilleres" - ] - }, - "Web/API/WindowOrWorkerGlobalScope/clearInterval": { - "modified": "2020-10-15T21:18:22.478Z", - "contributors": [ - "SphinxKnight", - "faflo10", - "Shinomix", - "fscholz", - "teoli", - "khalid32", - "Mgjbot", - "BenoitL" - ] - }, - "Web/API/WindowOrWorkerGlobalScope/crossOriginIsolated": { - "modified": "2020-10-15T22:26:34.641Z", - "contributors": [ - "Eliastik" - ] - }, - "Web/API/WindowOrWorkerGlobalScope/fetch": { - "modified": "2020-11-16T08:26:54.613Z", - "contributors": [ - "JNa0", - "PxlCtzn", - "fscholz", - "Hell_Carlito", - "Bat41" - ] - }, - "Web/API/WindowOrWorkerGlobalScope/indexedDB": { - "modified": "2020-10-15T21:45:39.555Z", - "contributors": [ - "Arzak656", - "SphinxKnight", - "gadgino" - ] - }, - "Web/API/WindowOrWorkerGlobalScope/isSecureContext": { - "modified": "2020-10-15T22:06:53.371Z", - "contributors": [ - "jonasgrilleres" - ] - }, - "Web/API/WindowOrWorkerGlobalScope/origin": { - "modified": "2020-10-15T22:06:53.236Z", - "contributors": [ - "jonasgrilleres" - ] - }, - "Web/API/WindowOrWorkerGlobalScope/queueMicrotask": { - "modified": "2020-10-15T22:26:44.474Z", - "contributors": [ - "Eliastik" - ] - }, - "Web/API/WindowOrWorkerGlobalScope/setTimeout": { - "modified": "2020-10-15T21:13:52.309Z", - "contributors": [ - "SphinxKnight", - "jmh", - "fscholz", - "teoli", - "jsx", - "Automatik", - "zanz", - "Tiller", - "Ceth", - "BenoitL", - "Mgjbot" - ] - }, "Web/API/Worker": { "modified": "2020-10-15T21:25:14.944Z", "contributors": [ @@ -22017,6 +21911,84 @@ "BenoitL" ] }, + "Web/API/atob": { + "modified": "2019-09-24T09:32:03.862Z", + "contributors": [ + "NemoNobobyPersonne", + "tbroadley", + "fscholz", + "teoli", + "khalid32", + "Mgjbot", + "BenoitL", + "Celelibi" + ] + }, + "Web/API/btoa": { + "modified": "2019-03-18T21:13:03.287Z", + "contributors": [ + "PamProg", + "NemoNobobyPersonne", + "teoli", + "lovasoa", + "fscholz", + "jsx", + "e7d", + "Mgjbot", + "BenoitL", + "Celelibi" + ] + }, + "Web/API/caches": { + "modified": "2020-10-15T22:06:53.037Z", + "contributors": [ + "Arzak656", + "jonasgrilleres" + ] + }, + "Web/API/clearInterval": { + "modified": "2020-10-15T21:18:22.478Z", + "contributors": [ + "SphinxKnight", + "faflo10", + "Shinomix", + "fscholz", + "teoli", + "khalid32", + "Mgjbot", + "BenoitL" + ] + }, + "Web/API/crossOriginIsolated": { + "modified": "2020-10-15T22:26:34.641Z", + "contributors": [ + "Eliastik" + ] + }, + "Web/API/fetch": { + "modified": "2020-11-16T08:26:54.613Z", + "contributors": [ + "JNa0", + "PxlCtzn", + "fscholz", + "Hell_Carlito", + "Bat41" + ] + }, + "Web/API/indexedDB": { + "modified": "2020-10-15T21:45:39.555Z", + "contributors": [ + "Arzak656", + "SphinxKnight", + "gadgino" + ] + }, + "Web/API/isSecureContext": { + "modified": "2020-10-15T22:06:53.371Z", + "contributors": [ + "jonasgrilleres" + ] + }, "Web/API/notification": { "modified": "2020-10-15T21:26:50.253Z", "contributors": [ @@ -22172,6 +22144,34 @@ "tomderudder" ] }, + "Web/API/origin": { + "modified": "2020-10-15T22:06:53.236Z", + "contributors": [ + "jonasgrilleres" + ] + }, + "Web/API/queueMicrotask": { + "modified": "2020-10-15T22:26:44.474Z", + "contributors": [ + "Eliastik" + ] + }, + "Web/API/setTimeout": { + "modified": "2020-10-15T21:13:52.309Z", + "contributors": [ + "SphinxKnight", + "jmh", + "fscholz", + "teoli", + "jsx", + "Automatik", + "zanz", + "Tiller", + "Ceth", + "BenoitL", + "Mgjbot" + ] + }, "Web/API/window/location": { "modified": "2019-03-23T23:59:30.762Z", "contributors": [ diff --git a/files/fr/web/api/atob/index.html b/files/fr/web/api/atob/index.html new file mode 100644 index 0000000000..bcc94f59e4 --- /dev/null +++ b/files/fr/web/api/atob/index.html @@ -0,0 +1,78 @@ +--- +title: window.atob +slug: Web/API/atob +tags: + - API + - DOM + - Reference + - WindowOrWorkerGlobalScope + - atob +translation_of: Web/API/WindowOrWorkerGlobalScope/atob +original_slug: Web/API/WindowOrWorkerGlobalScope/atob +--- +

{{APIRef ("HTML DOM")}}
+ La fonction WindowOrWorkerGlobalScope.atob() décode une chaîne de données qui a été codée en utilisant le codage en base 64. Vous pouvez utiliser la méthode {{domxref("WindowOrWorkerGlobalScope.btoa","btoa()")}} pour encoder et transmettre des données qui pourraient causer des problèmes de communication, puis les transmettre et utiliser la méthode atob() pour décoder les données . Par exemple, vous pouvez coder, transmettre et décoder des caractères de contrôle tels que les valeurs ASCII 0 à 31.

+ +

Pour une utilisation avec des chaînes Unicode ou UTF-8, voir cette note sur l'encodage et le décodage Base64 et cette note sur btoa().

+ +

Syntaxe

+ +
var donneesDecodees = scope.atob(donneesEncodees);
+
+ +

Déclenche

+ +

Déclenche une {{jsxref("DOMException")}} si la longueur de la chaîne passée en entrée n'est pas un multiple de 4.

+ +

Exemple

+ +
donneesEncodees = window.btoa('Salut, monde'); // encode une chaîne
+donneesDecodees = window.atob(donneesEncodees); // décode la chaîne
+
+ +

Spécifications

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SpécificationStatutCommentaire
{{SpecName('HTML WHATWG', 'webappapis.html#dom-btoa', 'WindowOrWorkerGlobalScope.atob()')}}{{Spec2('HTML WHATWG')}}Méthode déplacée dans le mixin WindowOrWorkerGlobalScope dans la spéc la plus récente.
{{SpecName('HTML WHATWG', '#dom-windowbase64-atob', 'WindowBase64.atob()')}}{{Spec2('HTML WHATWG')}}Pas de changement depuis l'instantané le plus récent {{SpecName("HTML5.1")}}.
{{SpecName('HTML5.1', '#dom-windowbase64-atob', 'WindowBase64.atob()')}}{{Spec2('HTML5.1')}}Instantané de {{SpecName("HTML WHATWG")}}. Pas de changement.
{{SpecName("HTML5 W3C", "#dom-windowbase64-atob", "WindowBase64.atob()")}}{{Spec2('HTML5 W3C')}}Instantané de {{SpecName("HTML WHATWG")}}. Création de WindowBase64 (les propriétés se trouvaient sur la cible avant cela).
+ +

Compatibilité des navigateurs

+ +

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

+ +

Voir aussi

+ + diff --git a/files/fr/web/api/btoa/index.html b/files/fr/web/api/btoa/index.html new file mode 100644 index 0000000000..9c07b8bb40 --- /dev/null +++ b/files/fr/web/api/btoa/index.html @@ -0,0 +1,123 @@ +--- +title: WindowBase64.btoa() +slug: Web/API/btoa +tags: + - API + - DOM + - Méthode + - Reference + - Web + - WindowOrWorkerGlobalScope + - btoa + - chaînes + - données +translation_of: Web/API/WindowOrWorkerGlobalScope/btoa +original_slug: Web/API/WindowOrWorkerGlobalScope/btoa +--- +
{{APIRef("HTML DOM")}}
+ +

La méthode WindowOrWorkerGlobalScope.btoa() crée une chaîne ASCII codée en base 64 à partir d'un objet {{jsxref ("String")}} dans lequel chaque caractère de la chaîne est traité comme un octet de données binaires.

+ +
+

Note : étant donné que cette fonction traite chaque caractère comme un octet de données binaires, quel que soit le nombre d'octets composant le caractère, une exception InvalidCharacterError est déclenchée si le {{Glossary("code point")}} d'un caractère quelconque est en dehors de la plage 0x00 à 0xFF. Voir {{anch("Chaînes Unicode")}} pour un exemple montrant comment encoder des chaînes avec des caractères en dehors de la plage 0x00 à 0xFF.

+
+ +

Syntaxe

+ +
var donneesEncodees = scope.btoa(chaineAEncoder);
+
+ +

Paramètres

+ +
+
chaineAEncoder
+
Une chaîne dont les caractères représentent chacun un octet unique de données binaires à encoder en ASCII.
+
+ +

Valeur retournée

+ +

Une chaîne contenant la représentation Base64 de la chaineAEncoder.

+ +

Exceptions

+ +

Exemple

+ +
var donneesEncodees = window.btoa('Salut, monde'); // encode une chaîne
+var donneesDecodees = window.atob(donneesEncodees); // décode la chaîne
+
+ +

Notes

+ +

Vous pouvez utiliser cette méthode pour encoder des données qui, autrement, pourraient engendrer des problèmes de communication, les transmettre et utiliser alors la méthode {{domxref("WindowOrWorkerGlobalScope.atob","atob()")}} pour décoder les données à nouveau. Par exemple, vous pouvez encoder des caractères de contrôle tels que les valeurs ASCII de 0 à 31.

+ +

btoa() est également disponible pour les composants XPCOM implémentés en JavaScript, même si {domxref("Window")}} n'est pas l'objet global dans les composants.

+ +

Chaînes Unicode

+ +

Dans la plupart des navigateurs, l'appel de btoa() sur une chaîne Unicode engendrera une exception InvalidCharacterError.

+ +

Une option est d'échapper tous les caractères étendus, de telle sorte que la chaîne que vous voulez en fait encoder soit une représentation ASCII de l'original. Voyez cet exemple, noté par Johan Sundström :

+ +
// Chaîne ucs-2 en ascii encodé en base64
+function uena(chn) {
+    return window.btoa(unescape(encodeURIComponent(chn)));
+}
+// Ascii encodé en base64 en chaîne ucs-2
+function aenu(chn) {
+    return decodeURIComponent(escape(window.atob(chn)));
+}
+// Usage :
+uena('✓ à la mode'); // 4pyTIMOgIGxhIG1vZGU=
+aenu('4pyTIMOgIGxhIG1vZGU='); // "✓ à la mode"
+
+uena('I \u2661 Unicode!'); // SSDimaEgVW5pY29kZSE=
+aenu('SSDimaEgVW5pY29kZSE='); // "I ♡ Unicode!"
+ +

Une solution meilleure, plus fiable et moins coûteuse consiste à utiliser des tableaux typés pour faire la conversion.

+ +

Spécifications

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SpécificationStatutCommentaire
{{SpecName('HTML WHATWG', 'webappapis.html#dom-btoa', 'WindowOrWorkerGlobalScope.btoa()')}}{{Spec2('HTML WHATWG')}}Méthode déplacée dans le mixin WindowOrWorkerGlobalScope dans la spéc la plus récente.
{{SpecName('HTML WHATWG', '#dom-windowbase64-btoa', 'WindowBase64.btoa()')}}{{Spec2('HTML WHATWG')}}Pas de changement depuis le dernier instantané, {{SpecName("HTML5.1")}}.
{{SpecName('HTML5.1', '#dom-windowbase64-btoa', 'WindowBase64.btoa()')}}{{Spec2('HTML5.1')}}Instantané de {{SpecName("HTML WHATWG")}}. Pas de changement.
{{SpecName("HTML5 W3C", "#dom-windowbase64-btoa", "WindowBase64.btoa()")}}{{Spec2('HTML5 W3C')}}Instantané de {{SpecName("HTML WHATWG")}}. Création de WindowBase64 (les propriétés se trouvaient sur la cible avant cela).
+ +

Compatibilité des navigateurs

+ +

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

+ +

Voir aussi

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

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

+ +

La propriété en lecture seule  caches de l'interface {{domxref("WindowOrWorkerGlobalScope")}} retourne l'objet {{domxref("CacheStorage")}} associé au contexte actuel. Cet objet permet de stocker des ressources pour une utilisation hors-ligne et de générer des réponses personnalisées à des requêtes.

+ +

Syntaxe

+ +
var myCacheStorage = self.caches; // ou simplement caches
+
+ +

Value

+ +

Un objet de type {{domxref("CacheStorage")}}.

+ +

Exemple

+ +

L'exemple suivant montre comment mettre en cache un contexte de service worker pour stocker des ressources et les utiliser hors-ligne.

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

Spécifications

+ + + + + + + + + + + + + + + + + + + +
SpécificationStatusComment
{{SpecName('Service Workers', '#self-caches', 'caches')}}{{Spec2('Service Workers')}} +

Défini dans un WindowOrWorkerGlobalScope partiel dans la nouvelle spec.

+
{{SpecName('Service Workers')}}{{Spec2('Service Workers')}}Définition initiale.
+ +

Compatibilité des navigateurs

+ + + +

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

+ +

Voir aussi

+ + diff --git a/files/fr/web/api/clearinterval/index.html b/files/fr/web/api/clearinterval/index.html new file mode 100644 index 0000000000..f65d566b16 --- /dev/null +++ b/files/fr/web/api/clearinterval/index.html @@ -0,0 +1,72 @@ +--- +title: WindowOrWorkerGlobalScope.clearInterval() +slug: Web/API/clearInterval +tags: + - API + - Méthode + - Reference + - WindowOrWorkerGlobalScope + - clearInterval +translation_of: Web/API/WindowOrWorkerGlobalScope/clearInterval +original_slug: Web/API/WindowOrWorkerGlobalScope/clearInterval +--- +
{{APIRef("HTML DOM")}}
+ +

La méthode clearInterval(), rattachée au mixin {{domxref("WindowOrWorkerGlobalScope")}}, permet d'annuler une action répétée minutée initiée via un appel à {{domxref("WindowOrWorkerGlobalScope.setInterval", "setInterval()")}}.

+ +

Syntaxe

+ +
scope.clearInterval(intervalID)
+
+ +

Paramètres

+ +
+
intervalID
+
L'identifiant de l'intervalle de répétition qu'on souhaite annuler. Cet identifiant est renvoyé lorsqu'on appelle setInterval() pour définir l'intervalle de répétition.
+
+ +

On notera que l'ensemble des identifiants utilisés est commun entre ceux fournis par {{domxref("WindowOrWorkerGlobalScope.setInterval", "setInterval()")}} et ceux fournis par {{domxref("WindowOrWorkerGlobalScope.setTimeout", "setTimeout()")}}. Cela signifie qu'on peut, techniquement, utiliser clearInterval() et {{domxref("WindowOrWorkerGlobalScope.clearTimeout", "clearTimeout()")}} de façon interchangeable. C'est toutefois une mauvaise pratique, qui nuit à la lisibilité du code et à sa maintenabilité.

+ +

Valeur de retour

+ +

{{jsxref("undefined")}}

+ +

Exemples

+ +

Voir l'exemple setInterval().

+ +

Spécifications

+ + + + + + + + + + + + + + + + + + + +
SpécificationÉtatCommentaires
{{SpecName('HTML WHATWG', 'webappapis.html#dom-clearinterval', 'WindowOrWorkerGlobalScope.clearInterval()')}}{{Spec2("HTML WHATWG")}}Cette méthode a été déplacée sur le mixin WindowOrWorkerGlobalScope.
{{SpecName('HTML WHATWG', 'webappapis.html#dom-clearinterval', 'clearInterval()')}}{{Spec2('HTML WHATWG')}} 
+ +

Compatibilité des navigateurs

+ +

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

+ +

Voir aussi

+ +
    +
  • {{domxref("WindowOrWorkerGlobalScope.setTimeout")}}
  • +
  • {{domxref("WindowOrWorkerGlobalScope.setInterval")}}
  • +
  • {{domxref("WindowOrWorkerGlobalScope.clearTimeout")}}
  • +
  • {{domxref("Window.requestAnimationFrame")}}
  • +
diff --git a/files/fr/web/api/crossoriginisolated/index.html b/files/fr/web/api/crossoriginisolated/index.html new file mode 100644 index 0000000000..0fd49fde85 --- /dev/null +++ b/files/fr/web/api/crossoriginisolated/index.html @@ -0,0 +1,59 @@ +--- +title: WindowOrWorkerGlobalScope.crossOriginIsolated +slug: Web/API/crossOriginIsolated +translation_of: Web/API/WindowOrWorkerGlobalScope/crossOriginIsolated +original_slug: Web/API/WindowOrWorkerGlobalScope/crossOriginIsolated +--- +
{{APIRef()}}{{SeeCompatTable}}
+ +

La propriéte en lecture seule crossOriginIsolated de l'interface {{domxref("WindowOrWorkerGlobalScope")}} retourne une valeur booléenne qui indique si un {{jsxref("SharedArrayBuffer")}} peut être envoyé via un appel à {{domxref("Window.postMessage()")}}.

+ +

Cette valeur est dépendante de toute entête {{httpheader("Cross-Origin-Opener-Policy")}} et {{httpheader("Cross-Origin-Embedder-Policy")}} présente dans la réponse.

+ +

Syntaxe

+ +
var myCrossOriginIsolated = self.crossOriginIsolated; // or just crossOriginIsolated
+
+ +

Valeur

+ +

Une valeur booléenne

+ +

Exemples

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

Spécifications

+ + + + + + + + + + + + + + +
SpécificationStatutCommentaire
{{SpecName("HTML WHATWG")}}Pas encore ajouté à la spécification
+ +

Compatibilité des navigateurs

+ + + +

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

+ +

Voir aussi

+ + diff --git a/files/fr/web/api/fetch/index.html b/files/fr/web/api/fetch/index.html new file mode 100644 index 0000000000..f339f8f389 --- /dev/null +++ b/files/fr/web/api/fetch/index.html @@ -0,0 +1,194 @@ +--- +title: GlobalFetch.fetch() +slug: Web/API/fetch +tags: + - API + - API Fetch + - Experimental + - Fetch + - GlobalFetch + - Méthode + - Reference + - WindowOrWorkerGlobalScope + - requête +translation_of: Web/API/WindowOrWorkerGlobalScope/fetch +original_slug: Web/API/WindowOrWorkerGlobalScope/fetch +--- +

{{APIRef("Fetch")}}

+ +

La méthode fetch() du mixin {{domxref("WindowOrWorkerGlobalScope")}} démarre le chargement d'une ressource sur le réseau et retourne une promesse qui est résolue dès que la réponse est disponible. La promesse résoud l'objet {{domxref("Response")}} représentant la réponse de votre requête. Cette promesse n'échoue pas en cas d'erreur HTTP, elle n'échoue que sur les problèmes de réseau. Vous devez utiliser un gestionnaire then pour identifier les erreurs HTTP.

+ +

WindowOrWorkerGlobalScope est aussi bien implémenté par {{domxref("Window")}} que par {{domxref("WorkerGlobalScope")}}, ce qui signifie que la méthode fetch() est disponible dans la plupart des cas où vous pourriez en avoir besoin.

+ +

Une promesse {{domxref("GlobalFetch.fetch","fetch()")}} n'est rejetée que quand un problème de réseau est rencontré, même si en réalité cela signifie généralement qu'il y a un problème de permissions ou quelque chose de similaire. La promesse ne sera pas rejetée en cas d'erreur HTTP (404, etc.) Pour cela, un gestionnaire then() doit vérifier que la propriété {{domxref("Response.ok")}} ait bien pour valeur true et/ou la valeur de la propriété {{domxref("Response.status")}}.

+ +

La méthode fetch() est contrôlée par la directive connect-src de l'entête Content Security Policy plutôt que par la directive de la ressource qui est récupérée.

+ +
+

Les paramètres de la méthode fetch() sont identiques à ceux du contructeur d'une {{domxref("Request.Request","Request()")}}.

+
+ +

Syntaxe

+ +
const fetchResponsePromise = Promise<Response> fetch(entrée[, init]);
+ +

Paramètres

+ +
+
entrée
+
Définit la ressource que vous voulez obtenir. Cela peut être : +
    +
  • Un {{domxref("USVString")}} qui contient l'URL de la ressource à obtenir. Certains navigateurs acceptent blob: et data:.
  • +
  • Un objet {{domxref("Request")}}.
  • +
+
+
init {{optional_inline}}
+
+

Un objet qui contient les paramètres de votre requête. Les options possibles sont :

+ +
+
method
+
La méthode de la requête, par exemple GET ou POST.
+ +
headers
+
Les entêtes à ajouter à votre requête, contenues dans un objet {{domxref("Headers")}} ou dans un objet avec des {{domxref("ByteString")}} pour valeurs.
+ +
body
+
Le corps de votre requête. Cela peut être un {{domxref("Blob")}}, un {{domxref("BufferSource")}}, un {{domxref("FormData")}}, un {{domxref("URLSearchParams")}}, ou un {{domxref("USVString")}}. Notez cependant qu'une requête avec GET ou HEAD pour méthode ne peut pas avoir de corps.
+ +
mode
+
Le mode à utiliser pour cette requête, par exemple cors, no-cors, ou same-origin.
+ +
credentials
+
Les identifiants à utiliser pour cette requête : omit, same-origin, ou include. Pour envoyer automatiquement les cookies pour le domaine actuel, cette option doit être définie. À partir de Chrome 50, cette propriété peut aussi prendre un objet {{domxref("FederatedCredential")}} ou une instance de {{domxref("PasswordCredential")}}.
+ +
cache
+
Le comportement du cache pour cette requête : default, no-store, reload, no-cache, force-cache, ou only-if-cached.
+ +
redirect
+
Le mode de redirection à adopter pour cette requête : follow (suivre les redirections automatiquement), error (abandonner avec une erreur si une redirection a lieu), ou manual (gérer les redirections manuellement). Dans Chrome, la valeur par défaut était follow avant Chrome 47, mais à partir de cette version, c'est manual.
+ +
referrer
+
Un USVString qui vaut no-referrerclient, ou qui contient une URL. La valeur par défaut est client.
+ +
referrerPolicy
+
Spécifie la valeur de l'entête HTTP referer. Cela peut être no-referrer, no-referrer-when-downgrade, origin, origin-when-cross-origin ou unsafe-url.
+ +
integrity
+
Contient la valeur de l'intégrité de la sous-ressource de la requête (par exemple, sha256-BpfBw7ivV8q2jLiT13fxDYAe2tJllusRSZ273h2nFSE=).
+ +
keepalive
+
Peut être utilisée pour autoriser la requête à se poursuivre après la fermeture de la page. Une requête avec ce paramètre est équivalente à l'API {{domxref("Navigator.sendBeacon()")}}.
+ +
signal
+
Une instance de {{domxref("AbortSignal")}} vous permettant de communiquer avec une requête et de l'interrompre si vous le souhaitez via un {{domxref("AbortController")}}.
+
+
+
+ +

Valeur retournée

+ +

Une {{domxref("Promise")}} qui se résoud avec un object {{domxref("Response")}}.

+ +

Exceptions

+ +
+
AbortError
+
La requête a été interrompue à cause d'un appel à la méthode {{domxref("AbortController.abort", "abort()")}} de {{domxref("AbortController")}}.
+
TypeError
+
L'URL spécifié inclut des identifiants. Ces informations devraient plutôt être fournises via l'en-tête HTTP {{HTTPHeader("Authorization")}}.
+
+ +

Exemple

+ +

Dans notre exemple de requête avec fetch (voir cet exemple en direct) nous créons une nouvelle {{domxref("Request")}} avec le constructeur correspondant, puis on l'envoie en appellant fetch(). Comme nous récupérons une image, nous utilisons la méthode {{domxref("Body.blob()")}} sur la réponse pour lui donner le bon type MIME pour qu'elle soit gérée correctement, puis l'on crée l'URL correspondant à cet objet et on l'affiche dans un élément {{htmlelement("img")}}.

+ +
const monImage = document.querySelector('img');
+
+let maRequete = new Request('fleurs.jpg');
+
+fetch(maRequete)
+.then(function(reponse) {
+  if (!response.ok) {
+    throw new Error(`erreur HTTP! statut: ${reponse.status}`);
+  }
+  return reponse.blob();
+})
+.then(function(reponse) {
+  let URLobjet = URL.createObjectURL(reponse);
+  monImage.src = URLobjet;
+});
+ +

Dans notre exemple fetch avec initialisation et requête (voir cet exemple en direct) nous faisons la même chose à la différence que nous passons aussi un objet d'initalisation à la méthode fetch :

+ +
const monImage = document.querySelector('img');
+
+let mesEntetes = new Headers();
+mesEntetes.append('Content-Type', 'image/jpeg');
+
+const monInit = { method: 'GET',
+               headers: mesEntetes,
+               mode: 'cors',
+               cache: 'default' };
+
+let maRequete = new Request('fleurs.jpg');
+
+fetch(maRequete, monInit).then(function(reponse) {
+  ...
+});
+ +

Notez que vous pouvez aussi passer l'objet d'initialisation au constructeur de la requête pour obtenir le même effet, par exemple :

+ +
let maRequete = new Request('fleurs.jpg', monInit);
+ +

Vous pouvez aussi utiliser un objet litéral comme en-têtes dans votre objet d'initalisation.

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

Spécifications

+ + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatutCommentaire
{{SpecName('Fetch','#fetch-method','fetch()')}}{{Spec2('Fetch')}}Définie dans un WindowOrWorkerGlobalScope dans la nouvelle spécification.
{{SpecName('Fetch','#dom-global-fetch','fetch()')}}{{Spec2('Fetch')}}Définition initiale
{{SpecName('Credential Management')}}{{Spec2('Credential Management')}}Ajoute la possiblité d'utiliser une instance de {{domxref("FederatedCredential")}} ou de {{domxref("PasswordCredential")}} comme valeur de init.credentials.
+ +

Compatibilité des navigateurs

+ +

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

+ +

Voir aussi

+ + diff --git a/files/fr/web/api/indexeddb/index.html b/files/fr/web/api/indexeddb/index.html new file mode 100644 index 0000000000..7d8aaa0ed5 --- /dev/null +++ b/files/fr/web/api/indexeddb/index.html @@ -0,0 +1,77 @@ +--- +title: IDBEnvironment.indexedDB +slug: Web/API/indexedDB +tags: + - API + - IndexedDB + - Propriété + - Reference + - WindowOrWorkerGlobalScope +translation_of: Web/API/WindowOrWorkerGlobalScope/indexedDB +original_slug: Web/API/WindowOrWorkerGlobalScope/indexedDB +--- +
{{APIRef}}
+ +

La propriété indexedDB en lecture seule, rattachée au mixin {{domxref("WindowOrWorkerGlobalScope")}} fournit un mécanisme qui permet aux applications d'accéder aux bases de données indexées de façon asynchrone.

+ +

Syntaxe

+ +
var IDBFactory = self.indexedDB;
+ +

Valeur de retour

+ +

Un objet {{domxref("IDBFactory")}}.

+ +

Exemples

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

Spécifications

+ + + + + + + + + + + + + + + + + + + +
SpécificationÉtatCommentaires
{{SpecName('IndexedDB 2', '#dom-windoworworkerglobalscope-indexeddb', 'indexedDB')}}{{Spec2('IndexedDB 2')}}Rattachement partiel à WindowOrWorkerGlobalScope.
{{SpecName('IndexedDB', '#widl-IDBEnvironment-indexedDB', 'indexedDB')}}{{Spec2('IndexedDB')}}Définition initiale.
+ +

Compatibilité des navigateurs

+ +
+
+ + +

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

+
+
+ +

Voir aussi

+ +
    +
  • Utiliser IndexedDB
  • +
  • Initier une connexion : {{domxref("IDBDatabase")}}
  • +
  • Utiliser les transactions : {{domxref("IDBTransaction")}}
  • +
  • Définir un intervalle de clés : {{domxref("IDBKeyRange")}}
  • +
  • Récupérer et modifier les données : {{domxref("IDBObjectStore")}}
  • +
  • Utiliser les curseurs {{domxref("IDBCursor")}}
  • +
  • Exemple de référence : To-do Notifications (exemple live).
  • +
diff --git a/files/fr/web/api/issecurecontext/index.html b/files/fr/web/api/issecurecontext/index.html new file mode 100644 index 0000000000..be1a06cc17 --- /dev/null +++ b/files/fr/web/api/issecurecontext/index.html @@ -0,0 +1,47 @@ +--- +title: WindowOrWorkerGlobalScope.isSecureContext +slug: Web/API/isSecureContext +translation_of: Web/API/WindowOrWorkerGlobalScope/isSecureContext +original_slug: Web/API/WindowOrWorkerGlobalScope/isSecureContext +--- +

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

+ +

La propriété isSecureContext de l'interface {{domxref("WindowOrWorkerGlobalScope")}} retourne un booleen indiquant si le contexte actuel est sécurisé (true) ou pas (false).

+ +

Syntaxe

+ +
var isItSecure = self.isSecureContext; // ou simplement isSecureContext
+
+ +

Valeur

+ +

Un {{domxref("Boolean")}}.

+ +

Spécifications

+ + + + + + + + + + + + + + +
SpécificationsStatutCommentaires
{{SpecName('Secure Contexts', '#dom-windoworworkerglobalscope-issecurecontext', 'WindowOrWorkerGlobalScope.isSecureContext')}}{{Spec2('Secure Contexts')}}Définition initiale.
+ +

Compatibilité des navigateurs

+ + + +

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

+ +

Voir aussi

+ + diff --git a/files/fr/web/api/origin/index.html b/files/fr/web/api/origin/index.html new file mode 100644 index 0000000000..5fd2b80559 --- /dev/null +++ b/files/fr/web/api/origin/index.html @@ -0,0 +1,51 @@ +--- +title: WindowOrWorkerGlobalScope.origin +slug: Web/API/origin +translation_of: Web/API/WindowOrWorkerGlobalScope/origin +original_slug: Web/API/WindowOrWorkerGlobalScope/origin +--- +

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

+ +

La propriété origin de l'interface {{domxref("WindowOrWorkerGlobalScope")}} retourne l'origine du scope global, serialisé en chaîne de caractères.

+ +

Syntaxe

+ +
var myOrigin = self.origin; // ou simplement origin
+
+ +

Valeur

+ +

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

+ +

Exemples

+ +

Exécuté depuis un worker, le code suivant permet d'afficher en console le scope global de ce worker à chaque message reçu.

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

Si l'origine n'est pas sous la forme scheme/host/port (par exemple, si vous exécutez le code en local, via file://), origin retournera la chaîne de caractère "null".

+ +

Spécifications

+ + + + + + + + + + + + + + +
SpécificationStatutCommentaires
{{SpecName('HTML WHATWG', 'webappapis.html#dom-origin', 'WindowOrWorkerGlobalScope.origin')}}{{Spec2('HTML WHATWG')}}Définition initiale.
+ +

Compatibilité des navigateurs

+ + + +

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

diff --git a/files/fr/web/api/queuemicrotask/index.html b/files/fr/web/api/queuemicrotask/index.html new file mode 100644 index 0000000000..cced10b9e4 --- /dev/null +++ b/files/fr/web/api/queuemicrotask/index.html @@ -0,0 +1,118 @@ +--- +title: WindowOrWorkerGlobalScope.queueMicrotask() +slug: Web/API/queueMicrotask +tags: + - API + - Asynchrone + - HTML DOM + - Intervales + - JavaScript + - Micro-tâche + - Microtask + - Minuteurs + - Méthode + - Performance + - ServiceWorker + - SharedWorker + - Tâches + - Window + - WindowOrWorkerGlobalScope + - Worker + - queueMicrotask + - setTimeout +translation_of: Web/API/WindowOrWorkerGlobalScope/queueMicrotask +original_slug: Web/API/WindowOrWorkerGlobalScope/queueMicrotask +--- +
{{APIRef("HTML DOM")}}
+ +

La méthode queueMicrotask(), qui est exposée par {{domxref("Window")}} ou l'interface {{domxref("Worker")}}, met en file d'attente une micro-tâche qui doit être exécutée à un moment sûr avant que le contrôle soit retourné à la boucle d'événement du navigateur. La micro-tâche est une fonction courte qui doit être exécutée après que la tâche actuelle ait terminé son exécution et lorsqu'il n'y a pas d'autre code en attente d'exécution avant que le contrôle du contexte d'exécution soit retourné à la boucle d'événement du navigateur.

+ +

Cela permet à votre code de fonctionner sans interférer avec aucun autre code potentiellement à une plus haute priorité en attente, mais avant que le navigateur ne regagne le contrôle du contexte d'exécution, qui dépend potentiellement de la tâche que vous devez effectuer. Vous pouvez en apprendre plus sur comment utiliser les micro-tâches et pourquoi vous devriez le faire dans notre microtask guide.

+ +

L'importance des micro-tâches vient de leur possibilité d'effectuer des tâches de manière asynchrone mais dans un ordre spécifique. Voir Using microtasks in JavaScript with queueMicrotask() pour plus de détails.

+ +

Les micro-tâches sont particulièrement utiles pour les librairies et les frameworks qui doivent effectuer un nettoyage final ou d'autres tâches à exécuter avant le rendu.

+ +

queueMicrotask() est exposé dans la mixin {{domxref("WindowOrWorkerGlobalScope")}}.

+ +

Syntaxe

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

Paramètres

+ +
+
function
+
Une {{jsxref("function")}} qui doit être exécutée lorsque le moteur du navigateur détermine qu'il est sûr d'appeler votre code. Les micro-tâches mises en files d'attente sont exécutées après la fin de toutes les tâches en attente mais avant de céder le contrôle à la boucle d'événement du navigateur.
+
+ +

Valeur de retour

+ +

undefined.

+ +

Exemples

+ +
self.queueMicrotask(() => {
+  // function contents here
+})
+ +

Tiré de la spécification de queueMicrotask :

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

Lorsque queueMicrotask() n'est pas disponible

+ +

Le code ci-dessous est une prothèse d'émulation (polyfill) pour queueMicrotask(). Il crée une micro-tâche en utilisant une promesse qui se résout immédiatement, et utilise un timeout si la promesse ne peut pas être créée.

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

Spécifications

+ + + + + + + + + + + + + + +
SpécificationStatutCommentaire
{{SpecName("HTML WHATWG", "timers-and-user-prompts.html#microtask-queuing", "self.queueMicrotask()")}}{{Spec2("HTML WHATWG")}}Définition initiale
+ +

Compatibilité des navigateurs

+ +

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

+ +

Voir aussi

+ + diff --git a/files/fr/web/api/settimeout/index.html b/files/fr/web/api/settimeout/index.html new file mode 100644 index 0000000000..351b32953b --- /dev/null +++ b/files/fr/web/api/settimeout/index.html @@ -0,0 +1,361 @@ +--- +title: WindowOrWorkerGlobalScope.setTimeout() +slug: Web/API/setTimeout +tags: + - API + - HTML DOM + - Méthode + - Reference +translation_of: Web/API/WindowOrWorkerGlobalScope/setTimeout +original_slug: Web/API/WindowOrWorkerGlobalScope/setTimeout +--- +
{{APIRef("HTML DOM")}}
+ +

La méthode setTimeout(), rattachée au mixin  {{domxref("WindowOrWorkerGlobalScope")}} (et qui succède à window.setTimeout()) permet de définir un « minuteur » (timer) qui exécute une fonction ou un code donné après la fin du délai indiqué.

+ +

Syntaxe

+ +
var identifiant = scope.setTimeout(fonction[, delai, param1, param2, ...]);
+var identifiant = scope.setTimeout(fonction[, delai]);
+var identifiant = scope.setTimeout(code[, delai]);
+
+ +

Paramètres

+ +
+
function
+
Une fonction ({{jsxref("function")}}) qui doit être exécuté au déclenchement du minuteur après le temps imparti.
+
code
+
Une chaîne de caractères qui représente le code à exécuter. Cette chaîne est compilée et exécutée à l'expiration du minuteur. Pour des raisons analogues à celles exprimées avec {{jsxref("Objets_globaux/eval", "eval()")}}, cette syntaxe n'est pas recommandée.
+
delai {{optional_inline}}
+
La durée, exprimée en millisecondes, à attendre avant que la fonction indiquée soit exécutée. Par défaut, ce paramètre vaut 0, ce qui signifiie que la fonction est exécutée dès que possible. La durée réelle mesurée avant l'exécution de la fonction peut être supérieure à ce paramètre, voir la section ci-après.
+
param1, … , paramN {{optional_inline}}
+
D'autres paramètres qui seront passés à la fonction une fois que le temps est écoulé.
+
+ +
+

Note : La première syntaxe utilisant les paramètres supplémentaires ne fonctionne pas pour Internet Explorer 9 et les versions antérieures. Si vous souhaitez obtenir cette fonctionnalité pour ce navigateur, vous devrez utiliser une prothèse, voir ci-après.

+
+ +

Valeur de retour

+ +

La valeur renvoyée par la fonction est un entier qui représente un identifiant du minuteur créé par l'appel à setTimeout(). Cet identifiant pourra être passé à la méthode {{domxref("WindowOrWorkerGlobalScope.clearTimeout","clearTimeout()")}} afin d'annuler ce minuteur donné.

+ +

Il peut être utile de savoir que setTimeout() et {{domxref("WindowOrWorkerGlobalScope.setInterval", "setInterval()")}} partagent le même ensemble d'identifiants et que  clearTimeout() et {{domxref("WindowOrWorkerGlobalScope.clearInterval", "clearInterval()")}} sont, techniquement, interchangeables. Toutefois pour des raisons de lisibilité et de maintenance, mieux vaut les utiliser par paires plutôt que de les mélanger.

+ +

Le moteur d'exécution garantit qu'un identifiant donné ne sera pas réutilisé par un appel ultérieur à setTimeout() ou setInterval() pour un même objet (une fenêtre ou un worker). En revanche, différents objets possèdent chacun leurs ensembles d'identifiants.

+ +

Exemples

+ +

Dans l'exemple qui suit, on dispose deux boutons classiques auxquels on associe, via des gestionnaires d'évènements, des fonctions qui utilisent setTimeout() et clearTimeout(). Utiliser le premier bouton déclenchera un minuteur qui affichera une boîte de dialogue après deux secondes. L'identifiant est enregistré à la création du minuteur et on peut annuler le minuteur en cours en appuyant sur le deuxième bouton (dont la fonction associée au gestionnaire d'évènements utilise clearTimeout()).

+ +

HTML

+ +
<button onclick="delayedAlert();">
+  Affiche une alerte après deux secondes
+</button>
+<p></p>
+<button onclick="clearAlert();">
+  Annuler l'alerte avant qu'elle ne se déclenche
+</button>
+
+ +

JavaScript

+ +
var timeoutID;
+
+function delayedAlert() {
+  timeoutID = window.setTimeout(slowAlert, 2000);
+}
+
+function slowAlert() {
+  alert("C'était long…");
+}
+
+function clearAlert() {
+  window.clearTimeout(timeoutID);
+}
+
+ +

Résultat

+ +

{{EmbedLiveSample('Exemples')}}

+ +
+

Note : Voir aussi les exemples pour clearTimeout().

+
+ +

Prothèse d'émulation (polyfill)

+ +

S'il vous faut passer un ou plusieurs arguments à la fonction de rappel tout en prenant en charge Internet Explorer 9 et les versions antérieures, vous pouvez utiliser cette prothèse qui ajoute la prise en charge des paramètres additionnels :

+ +
/*\
+|*|
+|*|  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
+|*|
+\*/
+
+(function() {
+  setTimeout(function(arg1) {
+    if (arg1 === 'test') {
+      // l'argument est passé, pas besoin de prothèse
+      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') {
+    // l'argument est passé, pas besoin de prothèse
+      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');
+}())
+
+ +

Correctif ciblé sur IE

+ +

Si vous souhaitez ne cibler que IE 9 et antérieurs, vous pouvez utiliser les commentaires conditionnels 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
+@*/
+
+ +

Ou plutôt les commentaires conditionnels 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]-->
+
+ +

Autres méthodes de contournement

+ +

Vous pouvez également utiliser une fonction anonyme comme fonction de rappel (callback) :

+ +
var intervalID = setTimeout(function() {
+  maFonction('un', 'deux', 'trois');
+  }, 1000);
+
+ +

Voici une réécriture de l'exemple précédent avec les fonctions fléchées :

+ +
var intervalID = setTimeout(() => {
+  maFonction('un', 'deux', 'trois');
+  }, 1000);
+
+ +

On peut également utiliser {{jsxref("Function.prototype.bind()")}} :

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

Le problème « this »

+ +

Lorsqu'on passe une fonction à setTimeout(), cette fonction peut être appelée avec une valeur this qui n'est pas celle qu'on attend. Ce problème est expliqué en détails dans la référence JavaScriptJavaScript reference.

+ +

Explications

+ +

Le code exécuté par setTimeout() est appelé dans un contexte d'exécution différent de celui de la fonction où setTimeout a été appelé. Les règles usuelles pour la détermination de this s'appliquent : si this n'est pas défini lors de l'appel ou avec bind, la valeur par défaut sera l'objet global (global ou window) en mode non-strict ou {{jsxref("undefined")}} en mode strict. Aussi, le this utilisé par la fonction de rappel ne sera pas le même this que celui utilisé par la fonction ayant appelé setTimeout.

+ +
+

Note : La valeur par défaut pour this, lors de l'utilisation d'une fonction de rappel par setTimeout sera toujours l'objet window et pas la valeur undefined, même en mode strict.

+
+ +

Par exemple :

+ +
monTableau = ['zéro', 'un', 'deux'];
+monTableau.maMéthode = function (sPropriété) {
+    console.log(arguments.length > 0 ? this[sPropriété] : this);
+};
+
+monTableau.maMéthode();  // affichera "zéro,un,deux" dans la console
+monTableau.maMéthode(1); // affichera "un"
+ +

Le code qui précède fonctionne car lorsque maMéthode est appelée, this correspond à monTableau et qu'au sein de maMéthode, this[sPropriété] correspond alors à monTableau[sPropriété]. Toutefois, avec :

+ +
setTimeout(monTableau.maMéthode, 1000);
+// affiche "[object Window]" après 1 seconde
+setTimeout(monTableau.maMéthode, 1500, '1');
+// affiche "undefined" après 1.5 seconde
+ +

La fonction monTableau.maMéthode est pasée à setTimeout et, lorsqu'elle est appelée, this n'est pas défini et le moteur utilise la valeur par défaut : window. Il n'y apas d'option qui permettent de passer une valeur  thisArg à setTimeout() comme on peut le faire avec {{jsxref("Array.prototype.forEach()")}} ou {{jsxref("Array.prototype.reduce()")}} par exemple. Aussi, utiliser call() afin de définir this ne fonctionnera pas non plus.

+ +
setTimeout.call(monTableau, monTableau.maMéthode, 2000);
+// error: "NS_ERROR_XPC_BAD_OP_ON_WN_PROTO: Illegal operation on WrappedNative prototype object"
+setTimeout.call(monTableau, monTableau.maMéthode, 2500, 2);
+// même erreur
+
+ +

Solutions éventuelles

+ +

Note: JavaScript 1.8.5 introduced the Function.prototype.bind() method to set the value of this for all calls to a given function. This can avoid having to use a wrapper function to set the value of this in a callback.

+ +

Exemple d'utilisation :

+ +
var monTableau = ['zéro', 'un', 'deux'];
+var maMéthodeLiée = (function (sPropriété) {
+  console.log(arguments.length > 0 ? this[sPropriété] : this);
+}).bind(monTableau);
+
+
+maMéthodeLiée(); // affiche "zéro,un,deux"
+maMéthodeLiée(1); // affiche "un"
+setTimeout(maMéthodeLiée, 1000);
+// affiche "zéro,un,deux" après une seconde
+setTimeout(maMéthodeLiée, 1500, "1");
+// affiche "un" après 1.5 seconde
+
+ +

Notes

+ +

Les minuteurs peuvent être annulés avec {{domxref("WindowOrWorkerGlobalScope.clearTimeout","clearTimeout()")}}. Si on souhaite appeler une fonction de façon répétée, on utilisera plutôt {{domxref("WindowOrWorkerGlobalScope.setInterval()","setInterval()")}}.

+ +

Utiliser des chaînes pour le code plutôt que des fonctions

+ +

Passer une chaîne de caractères pour le code à exécuter, plutôt qu'une fonction, souffre des mêmes dangers que {{jsxref("Objets_globaux/eval","eval()")}}.

+ +
// Recommandé
+window.setTimeout(function() {
+    console.log('Coucou monde !');
+}, 500);
+
+// Non recommandé
+window.setTimeout("console.log('Coucou monde !');", 500);
+
+ +

Une chaîne de caractères passée à setTimeout sera évaluée dans le contexte global. Aussi, les symboles locaux au contexte de l'appel de setTimeout() ne seront pas accessibles au code présent dans la chaîne de caractères lors de son évaluation.

+ +

Durée plus longue que le paramètre indiquée

+ +

Plusieurs raisons peuvent expliquer une durée réelle plus longue que le délai passé en argument. Voici les plus fréquentes.

+ +

Précision minimale à 4ms

+ +

Dans les navigateurs récents les appels à setTimeout()/{{domxref("WindowOrworkerGlobalScope.setInterval","setInterval()")}} possèdent au plus une précision de 4ms lorsque plusieurs appels imbriqués sont réalisés. Par exemple :

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

Pour Chrome et Firefox, la limitation est active à partir du cinquième appel de fonction de rappel,  Safari active la limitation à partir du sixième et Edge à partir du troisième. Gecko traite setInterval() de la même façon depuis la version 56.

+ +

Par le passé, certains navigateurs implémentaient cette limite différemment (pour les appels à setInterval() quelle que soit leur provenance ou lorsqu'un appel setTimeout() était imbriqué dans un autre pour un certain nombre de niveaux d'imbrication.

+ +

Pour implémenter un minuteur de 0ms, on pourra utiliser {{domxref("window.postMessage()")}}.

+ +
+

Note : Le délai minimal est géré dans Firefox via une préférence : dom.min_timeout_value.

+
+ +
+

Note : Cette durée de 4 ms est définie dans la spécification HTML5 et est la même dans l'ensemble des navigateurs à partir de 2010. Avant {{geckoRelease("5.0")}}, la valeur minimale pour les appels imbriqués était 10ms.

+
+ +

Précision minimale des minuteurs pour les onglets inactifs : plus de 1000ms

+ +

Afin de réduire la charge (ainsi que la consommation d'énergie associée) des onglets en arrière-plan, les minuteurs ne sont déclenchés au maximum qu'une fois par seconde pour les onglets inactifs.

+ +

Firefox implémente ce comportement depuis Firefox 5 (cf.  {{bug(633421)}}) et la valeur du seuil de 1000ms peut être paramétrée via la préférence dom.min_background_timeout_value. Chrome implémente ce comportement depuis la version 11 (crbug.com/66078).

+ +

Firefox pour Android utilise un minimum de 15 minutes depuis Firefox 14 (cf.  {{bug(736602)}}) et les onglets en arrière-plan peuvent être déchargés complètement.

+ +
+

Note : Firefox 50 ne limite plus la réactivité des onglets en arrière-plan si un contexte Web Audio API {{domxref("AudioContext")}} joue un son. Firefox 51 élargit le spectre en supprimant la limitation si un objet {{domxref("AudioContext")}} est présent dans l'onglet, même sans jouer de son. Cela a permis de résoudre différents problèmes avec certaines applications qui jouent de la musique en arrière-plan.

+
+ +

Limitation des minuteurs pour les scripts de pistage

+ +

Depuis Firefox 55, les scripts de pistage (par exemple Google Analytics) (c'est-à-dire que toute URL que Firefox reconnaît comme appartenant à un domaine de pistage via la liste TP) ont une limitation plus forte. En premier plan la limitation est toujours de 4ms mais pour les onglets en arrière-plan, la limite est à 10000ms une fois que 30 secondes se sont écoulées après le premier chargement du document.

+ +

Ces seuils peuvent être gérés via les préférences :

+ +
    +
  • dom.min_tracking_timeout_value : 4
  • +
  • dom.min_tracking_background_timeout_value : 10000
  • +
  • dom.timeout.tracking_throttling_delay : 30000
  • +
+ +

Minuteurs en retard

+ +

En plus de ces limitations, le minuteur peut être déclenché plus tard si le navigateur ou le système d'opération est occupé sur d'autres tâches. On notera particulièrement que la fonction de rappel n'est pas exécutée tant que le thread du script n'a pas terminé. Par exemple :

+ +
function toto() {
+  console.log('appel de toto');
+}
+setTimeout(toto, 0);
+console.log('Après setTimeout');
+ +

affichera, dans la console :

+ +
Après setTimeout
+appel de toto
+ +

Ici, même si setTimeout a été appelé avec un délai nul, la fonction de rappel est placée dans la queue et est planifiée pour être exécutée dès que possible : ce qui n'est pas « immédiatement ». Le code courant doit finir d'être exécuté afin que les appels dans la queue puissent être dépilés.

+ +

Valeur de délai maximale

+ +

Les navigateurs que sont Internet Explorer, Chrome, Safari et Firefox stockent, en interne, la valeur du délai comme un entier sur 32 bits signé. Il y a donc un dépassement de borne si le délai est supérieur à 2147483647 millisecondes, ce qui correspond à 24.8 days. Si une telle valeur (supérieure à ce seuil) est utilisée, le minuteur est déclenché dès que possible.

+ +

Spécifications

+ + + + + + + + + + + + + + + + + + + +
SpécificationÉtatCommentaires
{{SpecName('HTML WHATWG', 'webappapis.html#dom-settimeout', 'WindowOrWorkerGlobalScope.setTimeout()')}}{{Spec2("HTML WHATWG")}}Déplacement de la méthode sur le mixin WindowOrWorkerGlobalScope dans la dernière spécification.
{{SpecName("HTML WHATWG", "webappapis.html#dom-settimeout", "WindowTimers.setTimeout()")}}{{Spec2("HTML WHATWG")}}Définition initiale (DOM Level 0)
+ +

Compatibilité des navigateurs

+ +

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

+ +

Voir aussi

+ +
    +
  • {{domxref("WindowOrWorkerGlobalScope.clearTimeout")}}
  • +
  • {{domxref("WindowOrWorkerGlobalScope.setInterval")}}
  • +
  • {{domxref("window.requestAnimationFrame")}}
  • +
diff --git a/files/fr/web/api/windoworworkerglobalscope/atob/index.html b/files/fr/web/api/windoworworkerglobalscope/atob/index.html deleted file mode 100644 index 1ce6ba94c1..0000000000 --- a/files/fr/web/api/windoworworkerglobalscope/atob/index.html +++ /dev/null @@ -1,78 +0,0 @@ ---- -title: window.atob -slug: Web/API/WindowOrWorkerGlobalScope/atob -tags: - - API - - DOM - - Reference - - WindowOrWorkerGlobalScope - - atob -translation_of: Web/API/WindowOrWorkerGlobalScope/atob -original_slug: Web/API/WindowBase64/atob ---- -

{{APIRef ("HTML DOM")}}
- La fonction WindowOrWorkerGlobalScope.atob() décode une chaîne de données qui a été codée en utilisant le codage en base 64. Vous pouvez utiliser la méthode {{domxref("WindowOrWorkerGlobalScope.btoa","btoa()")}} pour encoder et transmettre des données qui pourraient causer des problèmes de communication, puis les transmettre et utiliser la méthode atob() pour décoder les données . Par exemple, vous pouvez coder, transmettre et décoder des caractères de contrôle tels que les valeurs ASCII 0 à 31.

- -

Pour une utilisation avec des chaînes Unicode ou UTF-8, voir cette note sur l'encodage et le décodage Base64 et cette note sur btoa().

- -

Syntaxe

- -
var donneesDecodees = scope.atob(donneesEncodees);
-
- -

Déclenche

- -

Déclenche une {{jsxref("DOMException")}} si la longueur de la chaîne passée en entrée n'est pas un multiple de 4.

- -

Exemple

- -
donneesEncodees = window.btoa('Salut, monde'); // encode une chaîne
-donneesDecodees = window.atob(donneesEncodees); // décode la chaîne
-
- -

Spécifications

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
SpécificationStatutCommentaire
{{SpecName('HTML WHATWG', 'webappapis.html#dom-btoa', 'WindowOrWorkerGlobalScope.atob()')}}{{Spec2('HTML WHATWG')}}Méthode déplacée dans le mixin WindowOrWorkerGlobalScope dans la spéc la plus récente.
{{SpecName('HTML WHATWG', '#dom-windowbase64-atob', 'WindowBase64.atob()')}}{{Spec2('HTML WHATWG')}}Pas de changement depuis l'instantané le plus récent {{SpecName("HTML5.1")}}.
{{SpecName('HTML5.1', '#dom-windowbase64-atob', 'WindowBase64.atob()')}}{{Spec2('HTML5.1')}}Instantané de {{SpecName("HTML WHATWG")}}. Pas de changement.
{{SpecName("HTML5 W3C", "#dom-windowbase64-atob", "WindowBase64.atob()")}}{{Spec2('HTML5 W3C')}}Instantané de {{SpecName("HTML WHATWG")}}. Création de WindowBase64 (les propriétés se trouvaient sur la cible avant cela).
- -

Compatibilité des navigateurs

- -

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

- -

Voir aussi

- - diff --git a/files/fr/web/api/windoworworkerglobalscope/btoa/index.html b/files/fr/web/api/windoworworkerglobalscope/btoa/index.html deleted file mode 100644 index 41956ed3b0..0000000000 --- a/files/fr/web/api/windoworworkerglobalscope/btoa/index.html +++ /dev/null @@ -1,123 +0,0 @@ ---- -title: WindowBase64.btoa() -slug: Web/API/WindowOrWorkerGlobalScope/btoa -tags: - - API - - DOM - - Méthode - - Reference - - Web - - WindowOrWorkerGlobalScope - - btoa - - chaînes - - données -translation_of: Web/API/WindowOrWorkerGlobalScope/btoa -original_slug: Web/API/WindowBase64/btoa ---- -
{{APIRef("HTML DOM")}}
- -

La méthode WindowOrWorkerGlobalScope.btoa() crée une chaîne ASCII codée en base 64 à partir d'un objet {{jsxref ("String")}} dans lequel chaque caractère de la chaîne est traité comme un octet de données binaires.

- -
-

Note : étant donné que cette fonction traite chaque caractère comme un octet de données binaires, quel que soit le nombre d'octets composant le caractère, une exception InvalidCharacterError est déclenchée si le {{Glossary("code point")}} d'un caractère quelconque est en dehors de la plage 0x00 à 0xFF. Voir {{anch("Chaînes Unicode")}} pour un exemple montrant comment encoder des chaînes avec des caractères en dehors de la plage 0x00 à 0xFF.

-
- -

Syntaxe

- -
var donneesEncodees = scope.btoa(chaineAEncoder);
-
- -

Paramètres

- -
-
chaineAEncoder
-
Une chaîne dont les caractères représentent chacun un octet unique de données binaires à encoder en ASCII.
-
- -

Valeur retournée

- -

Une chaîne contenant la représentation Base64 de la chaineAEncoder.

- -

Exceptions

- -

Exemple

- -
var donneesEncodees = window.btoa('Salut, monde'); // encode une chaîne
-var donneesDecodees = window.atob(donneesEncodees); // décode la chaîne
-
- -

Notes

- -

Vous pouvez utiliser cette méthode pour encoder des données qui, autrement, pourraient engendrer des problèmes de communication, les transmettre et utiliser alors la méthode {{domxref("WindowOrWorkerGlobalScope.atob","atob()")}} pour décoder les données à nouveau. Par exemple, vous pouvez encoder des caractères de contrôle tels que les valeurs ASCII de 0 à 31.

- -

btoa() est également disponible pour les composants XPCOM implémentés en JavaScript, même si {domxref("Window")}} n'est pas l'objet global dans les composants.

- -

Chaînes Unicode

- -

Dans la plupart des navigateurs, l'appel de btoa() sur une chaîne Unicode engendrera une exception InvalidCharacterError.

- -

Une option est d'échapper tous les caractères étendus, de telle sorte que la chaîne que vous voulez en fait encoder soit une représentation ASCII de l'original. Voyez cet exemple, noté par Johan Sundström :

- -
// Chaîne ucs-2 en ascii encodé en base64
-function uena(chn) {
-    return window.btoa(unescape(encodeURIComponent(chn)));
-}
-// Ascii encodé en base64 en chaîne ucs-2
-function aenu(chn) {
-    return decodeURIComponent(escape(window.atob(chn)));
-}
-// Usage :
-uena('✓ à la mode'); // 4pyTIMOgIGxhIG1vZGU=
-aenu('4pyTIMOgIGxhIG1vZGU='); // "✓ à la mode"
-
-uena('I \u2661 Unicode!'); // SSDimaEgVW5pY29kZSE=
-aenu('SSDimaEgVW5pY29kZSE='); // "I ♡ Unicode!"
- -

Une solution meilleure, plus fiable et moins coûteuse consiste à utiliser des tableaux typés pour faire la conversion.

- -

Spécifications

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
SpécificationStatutCommentaire
{{SpecName('HTML WHATWG', 'webappapis.html#dom-btoa', 'WindowOrWorkerGlobalScope.btoa()')}}{{Spec2('HTML WHATWG')}}Méthode déplacée dans le mixin WindowOrWorkerGlobalScope dans la spéc la plus récente.
{{SpecName('HTML WHATWG', '#dom-windowbase64-btoa', 'WindowBase64.btoa()')}}{{Spec2('HTML WHATWG')}}Pas de changement depuis le dernier instantané, {{SpecName("HTML5.1")}}.
{{SpecName('HTML5.1', '#dom-windowbase64-btoa', 'WindowBase64.btoa()')}}{{Spec2('HTML5.1')}}Instantané de {{SpecName("HTML WHATWG")}}. Pas de changement.
{{SpecName("HTML5 W3C", "#dom-windowbase64-btoa", "WindowBase64.btoa()")}}{{Spec2('HTML5 W3C')}}Instantané de {{SpecName("HTML WHATWG")}}. Création de WindowBase64 (les propriétés se trouvaient sur la cible avant cela).
- -

Compatibilité des navigateurs

- -

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

- -

Voir aussi

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

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

- -

La propriété en lecture seule  caches de l'interface {{domxref("WindowOrWorkerGlobalScope")}} retourne l'objet {{domxref("CacheStorage")}} associé au contexte actuel. Cet objet permet de stocker des ressources pour une utilisation hors-ligne et de générer des réponses personnalisées à des requêtes.

- -

Syntaxe

- -
var myCacheStorage = self.caches; // ou simplement caches
-
- -

Value

- -

Un objet de type {{domxref("CacheStorage")}}.

- -

Exemple

- -

L'exemple suivant montre comment mettre en cache un contexte de service worker pour stocker des ressources et les utiliser hors-ligne.

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

Spécifications

- - - - - - - - - - - - - - - - - - - -
SpécificationStatusComment
{{SpecName('Service Workers', '#self-caches', 'caches')}}{{Spec2('Service Workers')}} -

Défini dans un WindowOrWorkerGlobalScope partiel dans la nouvelle spec.

-
{{SpecName('Service Workers')}}{{Spec2('Service Workers')}}Définition initiale.
- -

Compatibilité des navigateurs

- - - -

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

- -

Voir aussi

- - diff --git a/files/fr/web/api/windoworworkerglobalscope/clearinterval/index.html b/files/fr/web/api/windoworworkerglobalscope/clearinterval/index.html deleted file mode 100644 index d80eda07e3..0000000000 --- a/files/fr/web/api/windoworworkerglobalscope/clearinterval/index.html +++ /dev/null @@ -1,72 +0,0 @@ ---- -title: WindowOrWorkerGlobalScope.clearInterval() -slug: Web/API/WindowOrWorkerGlobalScope/clearInterval -tags: - - API - - Méthode - - Reference - - WindowOrWorkerGlobalScope - - clearInterval -translation_of: Web/API/WindowOrWorkerGlobalScope/clearInterval -original_slug: Web/API/WindowTimers/clearInterval ---- -
{{APIRef("HTML DOM")}}
- -

La méthode clearInterval(), rattachée au mixin {{domxref("WindowOrWorkerGlobalScope")}}, permet d'annuler une action répétée minutée initiée via un appel à {{domxref("WindowOrWorkerGlobalScope.setInterval", "setInterval()")}}.

- -

Syntaxe

- -
scope.clearInterval(intervalID)
-
- -

Paramètres

- -
-
intervalID
-
L'identifiant de l'intervalle de répétition qu'on souhaite annuler. Cet identifiant est renvoyé lorsqu'on appelle setInterval() pour définir l'intervalle de répétition.
-
- -

On notera que l'ensemble des identifiants utilisés est commun entre ceux fournis par {{domxref("WindowOrWorkerGlobalScope.setInterval", "setInterval()")}} et ceux fournis par {{domxref("WindowOrWorkerGlobalScope.setTimeout", "setTimeout()")}}. Cela signifie qu'on peut, techniquement, utiliser clearInterval() et {{domxref("WindowOrWorkerGlobalScope.clearTimeout", "clearTimeout()")}} de façon interchangeable. C'est toutefois une mauvaise pratique, qui nuit à la lisibilité du code et à sa maintenabilité.

- -

Valeur de retour

- -

{{jsxref("undefined")}}

- -

Exemples

- -

Voir l'exemple setInterval().

- -

Spécifications

- - - - - - - - - - - - - - - - - - - -
SpécificationÉtatCommentaires
{{SpecName('HTML WHATWG', 'webappapis.html#dom-clearinterval', 'WindowOrWorkerGlobalScope.clearInterval()')}}{{Spec2("HTML WHATWG")}}Cette méthode a été déplacée sur le mixin WindowOrWorkerGlobalScope.
{{SpecName('HTML WHATWG', 'webappapis.html#dom-clearinterval', 'clearInterval()')}}{{Spec2('HTML WHATWG')}} 
- -

Compatibilité des navigateurs

- -

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

- -

Voir aussi

- -
    -
  • {{domxref("WindowOrWorkerGlobalScope.setTimeout")}}
  • -
  • {{domxref("WindowOrWorkerGlobalScope.setInterval")}}
  • -
  • {{domxref("WindowOrWorkerGlobalScope.clearTimeout")}}
  • -
  • {{domxref("Window.requestAnimationFrame")}}
  • -
diff --git a/files/fr/web/api/windoworworkerglobalscope/crossoriginisolated/index.html b/files/fr/web/api/windoworworkerglobalscope/crossoriginisolated/index.html deleted file mode 100644 index cb7f6948a0..0000000000 --- a/files/fr/web/api/windoworworkerglobalscope/crossoriginisolated/index.html +++ /dev/null @@ -1,58 +0,0 @@ ---- -title: WindowOrWorkerGlobalScope.crossOriginIsolated -slug: Web/API/WindowOrWorkerGlobalScope/crossOriginIsolated -translation_of: Web/API/WindowOrWorkerGlobalScope/crossOriginIsolated ---- -
{{APIRef()}}{{SeeCompatTable}}
- -

La propriéte en lecture seule crossOriginIsolated de l'interface {{domxref("WindowOrWorkerGlobalScope")}} retourne une valeur booléenne qui indique si un {{jsxref("SharedArrayBuffer")}} peut être envoyé via un appel à {{domxref("Window.postMessage()")}}.

- -

Cette valeur est dépendante de toute entête {{httpheader("Cross-Origin-Opener-Policy")}} et {{httpheader("Cross-Origin-Embedder-Policy")}} présente dans la réponse.

- -

Syntaxe

- -
var myCrossOriginIsolated = self.crossOriginIsolated; // or just crossOriginIsolated
-
- -

Valeur

- -

Une valeur booléenne

- -

Exemples

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

Spécifications

- - - - - - - - - - - - - - -
SpécificationStatutCommentaire
{{SpecName("HTML WHATWG")}}Pas encore ajouté à la spécification
- -

Compatibilité des navigateurs

- - - -

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

- -

Voir aussi

- - diff --git a/files/fr/web/api/windoworworkerglobalscope/fetch/index.html b/files/fr/web/api/windoworworkerglobalscope/fetch/index.html deleted file mode 100644 index bb1399ba26..0000000000 --- a/files/fr/web/api/windoworworkerglobalscope/fetch/index.html +++ /dev/null @@ -1,193 +0,0 @@ ---- -title: GlobalFetch.fetch() -slug: Web/API/WindowOrWorkerGlobalScope/fetch -tags: - - API - - API Fetch - - Experimental - - Fetch - - GlobalFetch - - Méthode - - Reference - - WindowOrWorkerGlobalScope - - requête -translation_of: Web/API/WindowOrWorkerGlobalScope/fetch ---- -

{{APIRef("Fetch")}}

- -

La méthode fetch() du mixin {{domxref("WindowOrWorkerGlobalScope")}} démarre le chargement d'une ressource sur le réseau et retourne une promesse qui est résolue dès que la réponse est disponible. La promesse résoud l'objet {{domxref("Response")}} représentant la réponse de votre requête. Cette promesse n'échoue pas en cas d'erreur HTTP, elle n'échoue que sur les problèmes de réseau. Vous devez utiliser un gestionnaire then pour identifier les erreurs HTTP.

- -

WindowOrWorkerGlobalScope est aussi bien implémenté par {{domxref("Window")}} que par {{domxref("WorkerGlobalScope")}}, ce qui signifie que la méthode fetch() est disponible dans la plupart des cas où vous pourriez en avoir besoin.

- -

Une promesse {{domxref("GlobalFetch.fetch","fetch()")}} n'est rejetée que quand un problème de réseau est rencontré, même si en réalité cela signifie généralement qu'il y a un problème de permissions ou quelque chose de similaire. La promesse ne sera pas rejetée en cas d'erreur HTTP (404, etc.) Pour cela, un gestionnaire then() doit vérifier que la propriété {{domxref("Response.ok")}} ait bien pour valeur true et/ou la valeur de la propriété {{domxref("Response.status")}}.

- -

La méthode fetch() est contrôlée par la directive connect-src de l'entête Content Security Policy plutôt que par la directive de la ressource qui est récupérée.

- -
-

Les paramètres de la méthode fetch() sont identiques à ceux du contructeur d'une {{domxref("Request.Request","Request()")}}.

-
- -

Syntaxe

- -
const fetchResponsePromise = Promise<Response> fetch(entrée[, init]);
- -

Paramètres

- -
-
entrée
-
Définit la ressource que vous voulez obtenir. Cela peut être : -
    -
  • Un {{domxref("USVString")}} qui contient l'URL de la ressource à obtenir. Certains navigateurs acceptent blob: et data:.
  • -
  • Un objet {{domxref("Request")}}.
  • -
-
-
init {{optional_inline}}
-
-

Un objet qui contient les paramètres de votre requête. Les options possibles sont :

- -
-
method
-
La méthode de la requête, par exemple GET ou POST.
- -
headers
-
Les entêtes à ajouter à votre requête, contenues dans un objet {{domxref("Headers")}} ou dans un objet avec des {{domxref("ByteString")}} pour valeurs.
- -
body
-
Le corps de votre requête. Cela peut être un {{domxref("Blob")}}, un {{domxref("BufferSource")}}, un {{domxref("FormData")}}, un {{domxref("URLSearchParams")}}, ou un {{domxref("USVString")}}. Notez cependant qu'une requête avec GET ou HEAD pour méthode ne peut pas avoir de corps.
- -
mode
-
Le mode à utiliser pour cette requête, par exemple cors, no-cors, ou same-origin.
- -
credentials
-
Les identifiants à utiliser pour cette requête : omit, same-origin, ou include. Pour envoyer automatiquement les cookies pour le domaine actuel, cette option doit être définie. À partir de Chrome 50, cette propriété peut aussi prendre un objet {{domxref("FederatedCredential")}} ou une instance de {{domxref("PasswordCredential")}}.
- -
cache
-
Le comportement du cache pour cette requête : default, no-store, reload, no-cache, force-cache, ou only-if-cached.
- -
redirect
-
Le mode de redirection à adopter pour cette requête : follow (suivre les redirections automatiquement), error (abandonner avec une erreur si une redirection a lieu), ou manual (gérer les redirections manuellement). Dans Chrome, la valeur par défaut était follow avant Chrome 47, mais à partir de cette version, c'est manual.
- -
referrer
-
Un USVString qui vaut no-referrerclient, ou qui contient une URL. La valeur par défaut est client.
- -
referrerPolicy
-
Spécifie la valeur de l'entête HTTP referer. Cela peut être no-referrer, no-referrer-when-downgrade, origin, origin-when-cross-origin ou unsafe-url.
- -
integrity
-
Contient la valeur de l'intégrité de la sous-ressource de la requête (par exemple, sha256-BpfBw7ivV8q2jLiT13fxDYAe2tJllusRSZ273h2nFSE=).
- -
keepalive
-
Peut être utilisée pour autoriser la requête à se poursuivre après la fermeture de la page. Une requête avec ce paramètre est équivalente à l'API {{domxref("Navigator.sendBeacon()")}}.
- -
signal
-
Une instance de {{domxref("AbortSignal")}} vous permettant de communiquer avec une requête et de l'interrompre si vous le souhaitez via un {{domxref("AbortController")}}.
-
-
-
- -

Valeur retournée

- -

Une {{domxref("Promise")}} qui se résoud avec un object {{domxref("Response")}}.

- -

Exceptions

- -
-
AbortError
-
La requête a été interrompue à cause d'un appel à la méthode {{domxref("AbortController.abort", "abort()")}} de {{domxref("AbortController")}}.
-
TypeError
-
L'URL spécifié inclut des identifiants. Ces informations devraient plutôt être fournises via l'en-tête HTTP {{HTTPHeader("Authorization")}}.
-
- -

Exemple

- -

Dans notre exemple de requête avec fetch (voir cet exemple en direct) nous créons une nouvelle {{domxref("Request")}} avec le constructeur correspondant, puis on l'envoie en appellant fetch(). Comme nous récupérons une image, nous utilisons la méthode {{domxref("Body.blob()")}} sur la réponse pour lui donner le bon type MIME pour qu'elle soit gérée correctement, puis l'on crée l'URL correspondant à cet objet et on l'affiche dans un élément {{htmlelement("img")}}.

- -
const monImage = document.querySelector('img');
-
-let maRequete = new Request('fleurs.jpg');
-
-fetch(maRequete)
-.then(function(reponse) {
-  if (!response.ok) {
-    throw new Error(`erreur HTTP! statut: ${reponse.status}`);
-  }
-  return reponse.blob();
-})
-.then(function(reponse) {
-  let URLobjet = URL.createObjectURL(reponse);
-  monImage.src = URLobjet;
-});
- -

Dans notre exemple fetch avec initialisation et requête (voir cet exemple en direct) nous faisons la même chose à la différence que nous passons aussi un objet d'initalisation à la méthode fetch :

- -
const monImage = document.querySelector('img');
-
-let mesEntetes = new Headers();
-mesEntetes.append('Content-Type', 'image/jpeg');
-
-const monInit = { method: 'GET',
-               headers: mesEntetes,
-               mode: 'cors',
-               cache: 'default' };
-
-let maRequete = new Request('fleurs.jpg');
-
-fetch(maRequete, monInit).then(function(reponse) {
-  ...
-});
- -

Notez que vous pouvez aussi passer l'objet d'initialisation au constructeur de la requête pour obtenir le même effet, par exemple :

- -
let maRequete = new Request('fleurs.jpg', monInit);
- -

Vous pouvez aussi utiliser un objet litéral comme en-têtes dans votre objet d'initalisation.

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

Spécifications

- - - - - - - - - - - - - - - - - - - - - - - - -
SpecificationStatutCommentaire
{{SpecName('Fetch','#fetch-method','fetch()')}}{{Spec2('Fetch')}}Définie dans un WindowOrWorkerGlobalScope dans la nouvelle spécification.
{{SpecName('Fetch','#dom-global-fetch','fetch()')}}{{Spec2('Fetch')}}Définition initiale
{{SpecName('Credential Management')}}{{Spec2('Credential Management')}}Ajoute la possiblité d'utiliser une instance de {{domxref("FederatedCredential")}} ou de {{domxref("PasswordCredential")}} comme valeur de init.credentials.
- -

Compatibilité des navigateurs

- -

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

- -

Voir aussi

- - diff --git a/files/fr/web/api/windoworworkerglobalscope/indexeddb/index.html b/files/fr/web/api/windoworworkerglobalscope/indexeddb/index.html deleted file mode 100644 index b18f70c21f..0000000000 --- a/files/fr/web/api/windoworworkerglobalscope/indexeddb/index.html +++ /dev/null @@ -1,76 +0,0 @@ ---- -title: IDBEnvironment.indexedDB -slug: Web/API/WindowOrWorkerGlobalScope/indexedDB -tags: - - API - - IndexedDB - - Propriété - - Reference - - WindowOrWorkerGlobalScope -translation_of: Web/API/WindowOrWorkerGlobalScope/indexedDB ---- -
{{APIRef}}
- -

La propriété indexedDB en lecture seule, rattachée au mixin {{domxref("WindowOrWorkerGlobalScope")}} fournit un mécanisme qui permet aux applications d'accéder aux bases de données indexées de façon asynchrone.

- -

Syntaxe

- -
var IDBFactory = self.indexedDB;
- -

Valeur de retour

- -

Un objet {{domxref("IDBFactory")}}.

- -

Exemples

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

Spécifications

- - - - - - - - - - - - - - - - - - - -
SpécificationÉtatCommentaires
{{SpecName('IndexedDB 2', '#dom-windoworworkerglobalscope-indexeddb', 'indexedDB')}}{{Spec2('IndexedDB 2')}}Rattachement partiel à WindowOrWorkerGlobalScope.
{{SpecName('IndexedDB', '#widl-IDBEnvironment-indexedDB', 'indexedDB')}}{{Spec2('IndexedDB')}}Définition initiale.
- -

Compatibilité des navigateurs

- -
-
- - -

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

-
-
- -

Voir aussi

- -
    -
  • Utiliser IndexedDB
  • -
  • Initier une connexion : {{domxref("IDBDatabase")}}
  • -
  • Utiliser les transactions : {{domxref("IDBTransaction")}}
  • -
  • Définir un intervalle de clés : {{domxref("IDBKeyRange")}}
  • -
  • Récupérer et modifier les données : {{domxref("IDBObjectStore")}}
  • -
  • Utiliser les curseurs {{domxref("IDBCursor")}}
  • -
  • Exemple de référence : To-do Notifications (exemple live).
  • -
diff --git a/files/fr/web/api/windoworworkerglobalscope/issecurecontext/index.html b/files/fr/web/api/windoworworkerglobalscope/issecurecontext/index.html deleted file mode 100644 index e7f3c8c1fc..0000000000 --- a/files/fr/web/api/windoworworkerglobalscope/issecurecontext/index.html +++ /dev/null @@ -1,46 +0,0 @@ ---- -title: WindowOrWorkerGlobalScope.isSecureContext -slug: Web/API/WindowOrWorkerGlobalScope/isSecureContext -translation_of: Web/API/WindowOrWorkerGlobalScope/isSecureContext ---- -

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

- -

La propriété isSecureContext de l'interface {{domxref("WindowOrWorkerGlobalScope")}} retourne un booleen indiquant si le contexte actuel est sécurisé (true) ou pas (false).

- -

Syntaxe

- -
var isItSecure = self.isSecureContext; // ou simplement isSecureContext
-
- -

Valeur

- -

Un {{domxref("Boolean")}}.

- -

Spécifications

- - - - - - - - - - - - - - -
SpécificationsStatutCommentaires
{{SpecName('Secure Contexts', '#dom-windoworworkerglobalscope-issecurecontext', 'WindowOrWorkerGlobalScope.isSecureContext')}}{{Spec2('Secure Contexts')}}Définition initiale.
- -

Compatibilité des navigateurs

- - - -

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

- -

Voir aussi

- - diff --git a/files/fr/web/api/windoworworkerglobalscope/origin/index.html b/files/fr/web/api/windoworworkerglobalscope/origin/index.html deleted file mode 100644 index e0775b82bd..0000000000 --- a/files/fr/web/api/windoworworkerglobalscope/origin/index.html +++ /dev/null @@ -1,50 +0,0 @@ ---- -title: WindowOrWorkerGlobalScope.origin -slug: Web/API/WindowOrWorkerGlobalScope/origin -translation_of: Web/API/WindowOrWorkerGlobalScope/origin ---- -

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

- -

La propriété origin de l'interface {{domxref("WindowOrWorkerGlobalScope")}} retourne l'origine du scope global, serialisé en chaîne de caractères.

- -

Syntaxe

- -
var myOrigin = self.origin; // ou simplement origin
-
- -

Valeur

- -

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

- -

Exemples

- -

Exécuté depuis un worker, le code suivant permet d'afficher en console le scope global de ce worker à chaque message reçu.

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

Si l'origine n'est pas sous la forme scheme/host/port (par exemple, si vous exécutez le code en local, via file://), origin retournera la chaîne de caractère "null".

- -

Spécifications

- - - - - - - - - - - - - - -
SpécificationStatutCommentaires
{{SpecName('HTML WHATWG', 'webappapis.html#dom-origin', 'WindowOrWorkerGlobalScope.origin')}}{{Spec2('HTML WHATWG')}}Définition initiale.
- -

Compatibilité des navigateurs

- - - -

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

diff --git a/files/fr/web/api/windoworworkerglobalscope/queuemicrotask/index.html b/files/fr/web/api/windoworworkerglobalscope/queuemicrotask/index.html deleted file mode 100644 index e07291e3d5..0000000000 --- a/files/fr/web/api/windoworworkerglobalscope/queuemicrotask/index.html +++ /dev/null @@ -1,117 +0,0 @@ ---- -title: WindowOrWorkerGlobalScope.queueMicrotask() -slug: Web/API/WindowOrWorkerGlobalScope/queueMicrotask -tags: - - API - - Asynchrone - - HTML DOM - - Intervales - - JavaScript - - Micro-tâche - - Microtask - - Minuteurs - - Méthode - - Performance - - ServiceWorker - - SharedWorker - - Tâches - - Window - - WindowOrWorkerGlobalScope - - Worker - - queueMicrotask - - setTimeout -translation_of: Web/API/WindowOrWorkerGlobalScope/queueMicrotask ---- -
{{APIRef("HTML DOM")}}
- -

La méthode queueMicrotask(), qui est exposée par {{domxref("Window")}} ou l'interface {{domxref("Worker")}}, met en file d'attente une micro-tâche qui doit être exécutée à un moment sûr avant que le contrôle soit retourné à la boucle d'événement du navigateur. La micro-tâche est une fonction courte qui doit être exécutée après que la tâche actuelle ait terminé son exécution et lorsqu'il n'y a pas d'autre code en attente d'exécution avant que le contrôle du contexte d'exécution soit retourné à la boucle d'événement du navigateur.

- -

Cela permet à votre code de fonctionner sans interférer avec aucun autre code potentiellement à une plus haute priorité en attente, mais avant que le navigateur ne regagne le contrôle du contexte d'exécution, qui dépend potentiellement de la tâche que vous devez effectuer. Vous pouvez en apprendre plus sur comment utiliser les micro-tâches et pourquoi vous devriez le faire dans notre microtask guide.

- -

L'importance des micro-tâches vient de leur possibilité d'effectuer des tâches de manière asynchrone mais dans un ordre spécifique. Voir Using microtasks in JavaScript with queueMicrotask() pour plus de détails.

- -

Les micro-tâches sont particulièrement utiles pour les librairies et les frameworks qui doivent effectuer un nettoyage final ou d'autres tâches à exécuter avant le rendu.

- -

queueMicrotask() est exposé dans la mixin {{domxref("WindowOrWorkerGlobalScope")}}.

- -

Syntaxe

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

Paramètres

- -
-
function
-
Une {{jsxref("function")}} qui doit être exécutée lorsque le moteur du navigateur détermine qu'il est sûr d'appeler votre code. Les micro-tâches mises en files d'attente sont exécutées après la fin de toutes les tâches en attente mais avant de céder le contrôle à la boucle d'événement du navigateur.
-
- -

Valeur de retour

- -

undefined.

- -

Exemples

- -
self.queueMicrotask(() => {
-  // function contents here
-})
- -

Tiré de la spécification de queueMicrotask :

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

Lorsque queueMicrotask() n'est pas disponible

- -

Le code ci-dessous est une prothèse d'émulation (polyfill) pour queueMicrotask(). Il crée une micro-tâche en utilisant une promesse qui se résout immédiatement, et utilise un timeout si la promesse ne peut pas être créée.

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

Spécifications

- - - - - - - - - - - - - - -
SpécificationStatutCommentaire
{{SpecName("HTML WHATWG", "timers-and-user-prompts.html#microtask-queuing", "self.queueMicrotask()")}}{{Spec2("HTML WHATWG")}}Définition initiale
- -

Compatibilité des navigateurs

- -

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

- -

Voir aussi

- - diff --git a/files/fr/web/api/windoworworkerglobalscope/settimeout/index.html b/files/fr/web/api/windoworworkerglobalscope/settimeout/index.html deleted file mode 100644 index 6e676f6ebc..0000000000 --- a/files/fr/web/api/windoworworkerglobalscope/settimeout/index.html +++ /dev/null @@ -1,360 +0,0 @@ ---- -title: WindowOrWorkerGlobalScope.setTimeout() -slug: Web/API/WindowOrWorkerGlobalScope/setTimeout -tags: - - API - - HTML DOM - - Méthode - - Reference -translation_of: Web/API/WindowOrWorkerGlobalScope/setTimeout ---- -
{{APIRef("HTML DOM")}}
- -

La méthode setTimeout(), rattachée au mixin  {{domxref("WindowOrWorkerGlobalScope")}} (et qui succède à window.setTimeout()) permet de définir un « minuteur » (timer) qui exécute une fonction ou un code donné après la fin du délai indiqué.

- -

Syntaxe

- -
var identifiant = scope.setTimeout(fonction[, delai, param1, param2, ...]);
-var identifiant = scope.setTimeout(fonction[, delai]);
-var identifiant = scope.setTimeout(code[, delai]);
-
- -

Paramètres

- -
-
function
-
Une fonction ({{jsxref("function")}}) qui doit être exécuté au déclenchement du minuteur après le temps imparti.
-
code
-
Une chaîne de caractères qui représente le code à exécuter. Cette chaîne est compilée et exécutée à l'expiration du minuteur. Pour des raisons analogues à celles exprimées avec {{jsxref("Objets_globaux/eval", "eval()")}}, cette syntaxe n'est pas recommandée.
-
delai {{optional_inline}}
-
La durée, exprimée en millisecondes, à attendre avant que la fonction indiquée soit exécutée. Par défaut, ce paramètre vaut 0, ce qui signifiie que la fonction est exécutée dès que possible. La durée réelle mesurée avant l'exécution de la fonction peut être supérieure à ce paramètre, voir la section ci-après.
-
param1, … , paramN {{optional_inline}}
-
D'autres paramètres qui seront passés à la fonction une fois que le temps est écoulé.
-
- -
-

Note : La première syntaxe utilisant les paramètres supplémentaires ne fonctionne pas pour Internet Explorer 9 et les versions antérieures. Si vous souhaitez obtenir cette fonctionnalité pour ce navigateur, vous devrez utiliser une prothèse, voir ci-après.

-
- -

Valeur de retour

- -

La valeur renvoyée par la fonction est un entier qui représente un identifiant du minuteur créé par l'appel à setTimeout(). Cet identifiant pourra être passé à la méthode {{domxref("WindowOrWorkerGlobalScope.clearTimeout","clearTimeout()")}} afin d'annuler ce minuteur donné.

- -

Il peut être utile de savoir que setTimeout() et {{domxref("WindowOrWorkerGlobalScope.setInterval", "setInterval()")}} partagent le même ensemble d'identifiants et que  clearTimeout() et {{domxref("WindowOrWorkerGlobalScope.clearInterval", "clearInterval()")}} sont, techniquement, interchangeables. Toutefois pour des raisons de lisibilité et de maintenance, mieux vaut les utiliser par paires plutôt que de les mélanger.

- -

Le moteur d'exécution garantit qu'un identifiant donné ne sera pas réutilisé par un appel ultérieur à setTimeout() ou setInterval() pour un même objet (une fenêtre ou un worker). En revanche, différents objets possèdent chacun leurs ensembles d'identifiants.

- -

Exemples

- -

Dans l'exemple qui suit, on dispose deux boutons classiques auxquels on associe, via des gestionnaires d'évènements, des fonctions qui utilisent setTimeout() et clearTimeout(). Utiliser le premier bouton déclenchera un minuteur qui affichera une boîte de dialogue après deux secondes. L'identifiant est enregistré à la création du minuteur et on peut annuler le minuteur en cours en appuyant sur le deuxième bouton (dont la fonction associée au gestionnaire d'évènements utilise clearTimeout()).

- -

HTML

- -
<button onclick="delayedAlert();">
-  Affiche une alerte après deux secondes
-</button>
-<p></p>
-<button onclick="clearAlert();">
-  Annuler l'alerte avant qu'elle ne se déclenche
-</button>
-
- -

JavaScript

- -
var timeoutID;
-
-function delayedAlert() {
-  timeoutID = window.setTimeout(slowAlert, 2000);
-}
-
-function slowAlert() {
-  alert("C'était long…");
-}
-
-function clearAlert() {
-  window.clearTimeout(timeoutID);
-}
-
- -

Résultat

- -

{{EmbedLiveSample('Exemples')}}

- -
-

Note : Voir aussi les exemples pour clearTimeout().

-
- -

Prothèse d'émulation (polyfill)

- -

S'il vous faut passer un ou plusieurs arguments à la fonction de rappel tout en prenant en charge Internet Explorer 9 et les versions antérieures, vous pouvez utiliser cette prothèse qui ajoute la prise en charge des paramètres additionnels :

- -
/*\
-|*|
-|*|  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
-|*|
-\*/
-
-(function() {
-  setTimeout(function(arg1) {
-    if (arg1 === 'test') {
-      // l'argument est passé, pas besoin de prothèse
-      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') {
-    // l'argument est passé, pas besoin de prothèse
-      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');
-}())
-
- -

Correctif ciblé sur IE

- -

Si vous souhaitez ne cibler que IE 9 et antérieurs, vous pouvez utiliser les commentaires conditionnels 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
-@*/
-
- -

Ou plutôt les commentaires conditionnels 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]-->
-
- -

Autres méthodes de contournement

- -

Vous pouvez également utiliser une fonction anonyme comme fonction de rappel (callback) :

- -
var intervalID = setTimeout(function() {
-  maFonction('un', 'deux', 'trois');
-  }, 1000);
-
- -

Voici une réécriture de l'exemple précédent avec les fonctions fléchées :

- -
var intervalID = setTimeout(() => {
-  maFonction('un', 'deux', 'trois');
-  }, 1000);
-
- -

On peut également utiliser {{jsxref("Function.prototype.bind()")}} :

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

Le problème « this »

- -

Lorsqu'on passe une fonction à setTimeout(), cette fonction peut être appelée avec une valeur this qui n'est pas celle qu'on attend. Ce problème est expliqué en détails dans la référence JavaScriptJavaScript reference.

- -

Explications

- -

Le code exécuté par setTimeout() est appelé dans un contexte d'exécution différent de celui de la fonction où setTimeout a été appelé. Les règles usuelles pour la détermination de this s'appliquent : si this n'est pas défini lors de l'appel ou avec bind, la valeur par défaut sera l'objet global (global ou window) en mode non-strict ou {{jsxref("undefined")}} en mode strict. Aussi, le this utilisé par la fonction de rappel ne sera pas le même this que celui utilisé par la fonction ayant appelé setTimeout.

- -
-

Note : La valeur par défaut pour this, lors de l'utilisation d'une fonction de rappel par setTimeout sera toujours l'objet window et pas la valeur undefined, même en mode strict.

-
- -

Par exemple :

- -
monTableau = ['zéro', 'un', 'deux'];
-monTableau.maMéthode = function (sPropriété) {
-    console.log(arguments.length > 0 ? this[sPropriété] : this);
-};
-
-monTableau.maMéthode();  // affichera "zéro,un,deux" dans la console
-monTableau.maMéthode(1); // affichera "un"
- -

Le code qui précède fonctionne car lorsque maMéthode est appelée, this correspond à monTableau et qu'au sein de maMéthode, this[sPropriété] correspond alors à monTableau[sPropriété]. Toutefois, avec :

- -
setTimeout(monTableau.maMéthode, 1000);
-// affiche "[object Window]" après 1 seconde
-setTimeout(monTableau.maMéthode, 1500, '1');
-// affiche "undefined" après 1.5 seconde
- -

La fonction monTableau.maMéthode est pasée à setTimeout et, lorsqu'elle est appelée, this n'est pas défini et le moteur utilise la valeur par défaut : window. Il n'y apas d'option qui permettent de passer une valeur  thisArg à setTimeout() comme on peut le faire avec {{jsxref("Array.prototype.forEach()")}} ou {{jsxref("Array.prototype.reduce()")}} par exemple. Aussi, utiliser call() afin de définir this ne fonctionnera pas non plus.

- -
setTimeout.call(monTableau, monTableau.maMéthode, 2000);
-// error: "NS_ERROR_XPC_BAD_OP_ON_WN_PROTO: Illegal operation on WrappedNative prototype object"
-setTimeout.call(monTableau, monTableau.maMéthode, 2500, 2);
-// même erreur
-
- -

Solutions éventuelles

- -

Note: JavaScript 1.8.5 introduced the Function.prototype.bind() method to set the value of this for all calls to a given function. This can avoid having to use a wrapper function to set the value of this in a callback.

- -

Exemple d'utilisation :

- -
var monTableau = ['zéro', 'un', 'deux'];
-var maMéthodeLiée = (function (sPropriété) {
-  console.log(arguments.length > 0 ? this[sPropriété] : this);
-}).bind(monTableau);
-
-
-maMéthodeLiée(); // affiche "zéro,un,deux"
-maMéthodeLiée(1); // affiche "un"
-setTimeout(maMéthodeLiée, 1000);
-// affiche "zéro,un,deux" après une seconde
-setTimeout(maMéthodeLiée, 1500, "1");
-// affiche "un" après 1.5 seconde
-
- -

Notes

- -

Les minuteurs peuvent être annulés avec {{domxref("WindowOrWorkerGlobalScope.clearTimeout","clearTimeout()")}}. Si on souhaite appeler une fonction de façon répétée, on utilisera plutôt {{domxref("WindowOrWorkerGlobalScope.setInterval()","setInterval()")}}.

- -

Utiliser des chaînes pour le code plutôt que des fonctions

- -

Passer une chaîne de caractères pour le code à exécuter, plutôt qu'une fonction, souffre des mêmes dangers que {{jsxref("Objets_globaux/eval","eval()")}}.

- -
// Recommandé
-window.setTimeout(function() {
-    console.log('Coucou monde !');
-}, 500);
-
-// Non recommandé
-window.setTimeout("console.log('Coucou monde !');", 500);
-
- -

Une chaîne de caractères passée à setTimeout sera évaluée dans le contexte global. Aussi, les symboles locaux au contexte de l'appel de setTimeout() ne seront pas accessibles au code présent dans la chaîne de caractères lors de son évaluation.

- -

Durée plus longue que le paramètre indiquée

- -

Plusieurs raisons peuvent expliquer une durée réelle plus longue que le délai passé en argument. Voici les plus fréquentes.

- -

Précision minimale à 4ms

- -

Dans les navigateurs récents les appels à setTimeout()/{{domxref("WindowOrworkerGlobalScope.setInterval","setInterval()")}} possèdent au plus une précision de 4ms lorsque plusieurs appels imbriqués sont réalisés. Par exemple :

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

Pour Chrome et Firefox, la limitation est active à partir du cinquième appel de fonction de rappel,  Safari active la limitation à partir du sixième et Edge à partir du troisième. Gecko traite setInterval() de la même façon depuis la version 56.

- -

Par le passé, certains navigateurs implémentaient cette limite différemment (pour les appels à setInterval() quelle que soit leur provenance ou lorsqu'un appel setTimeout() était imbriqué dans un autre pour un certain nombre de niveaux d'imbrication.

- -

Pour implémenter un minuteur de 0ms, on pourra utiliser {{domxref("window.postMessage()")}}.

- -
-

Note : Le délai minimal est géré dans Firefox via une préférence : dom.min_timeout_value.

-
- -
-

Note : Cette durée de 4 ms est définie dans la spécification HTML5 et est la même dans l'ensemble des navigateurs à partir de 2010. Avant {{geckoRelease("5.0")}}, la valeur minimale pour les appels imbriqués était 10ms.

-
- -

Précision minimale des minuteurs pour les onglets inactifs : plus de 1000ms

- -

Afin de réduire la charge (ainsi que la consommation d'énergie associée) des onglets en arrière-plan, les minuteurs ne sont déclenchés au maximum qu'une fois par seconde pour les onglets inactifs.

- -

Firefox implémente ce comportement depuis Firefox 5 (cf.  {{bug(633421)}}) et la valeur du seuil de 1000ms peut être paramétrée via la préférence dom.min_background_timeout_value. Chrome implémente ce comportement depuis la version 11 (crbug.com/66078).

- -

Firefox pour Android utilise un minimum de 15 minutes depuis Firefox 14 (cf.  {{bug(736602)}}) et les onglets en arrière-plan peuvent être déchargés complètement.

- -
-

Note : Firefox 50 ne limite plus la réactivité des onglets en arrière-plan si un contexte Web Audio API {{domxref("AudioContext")}} joue un son. Firefox 51 élargit le spectre en supprimant la limitation si un objet {{domxref("AudioContext")}} est présent dans l'onglet, même sans jouer de son. Cela a permis de résoudre différents problèmes avec certaines applications qui jouent de la musique en arrière-plan.

-
- -

Limitation des minuteurs pour les scripts de pistage

- -

Depuis Firefox 55, les scripts de pistage (par exemple Google Analytics) (c'est-à-dire que toute URL que Firefox reconnaît comme appartenant à un domaine de pistage via la liste TP) ont une limitation plus forte. En premier plan la limitation est toujours de 4ms mais pour les onglets en arrière-plan, la limite est à 10000ms une fois que 30 secondes se sont écoulées après le premier chargement du document.

- -

Ces seuils peuvent être gérés via les préférences :

- -
    -
  • dom.min_tracking_timeout_value : 4
  • -
  • dom.min_tracking_background_timeout_value : 10000
  • -
  • dom.timeout.tracking_throttling_delay : 30000
  • -
- -

Minuteurs en retard

- -

En plus de ces limitations, le minuteur peut être déclenché plus tard si le navigateur ou le système d'opération est occupé sur d'autres tâches. On notera particulièrement que la fonction de rappel n'est pas exécutée tant que le thread du script n'a pas terminé. Par exemple :

- -
function toto() {
-  console.log('appel de toto');
-}
-setTimeout(toto, 0);
-console.log('Après setTimeout');
- -

affichera, dans la console :

- -
Après setTimeout
-appel de toto
- -

Ici, même si setTimeout a été appelé avec un délai nul, la fonction de rappel est placée dans la queue et est planifiée pour être exécutée dès que possible : ce qui n'est pas « immédiatement ». Le code courant doit finir d'être exécuté afin que les appels dans la queue puissent être dépilés.

- -

Valeur de délai maximale

- -

Les navigateurs que sont Internet Explorer, Chrome, Safari et Firefox stockent, en interne, la valeur du délai comme un entier sur 32 bits signé. Il y a donc un dépassement de borne si le délai est supérieur à 2147483647 millisecondes, ce qui correspond à 24.8 days. Si une telle valeur (supérieure à ce seuil) est utilisée, le minuteur est déclenché dès que possible.

- -

Spécifications

- - - - - - - - - - - - - - - - - - - -
SpécificationÉtatCommentaires
{{SpecName('HTML WHATWG', 'webappapis.html#dom-settimeout', 'WindowOrWorkerGlobalScope.setTimeout()')}}{{Spec2("HTML WHATWG")}}Déplacement de la méthode sur le mixin WindowOrWorkerGlobalScope dans la dernière spécification.
{{SpecName("HTML WHATWG", "webappapis.html#dom-settimeout", "WindowTimers.setTimeout()")}}{{Spec2("HTML WHATWG")}}Définition initiale (DOM Level 0)
- -

Compatibilité des navigateurs

- -

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

- -

Voir aussi

- -
    -
  • {{domxref("WindowOrWorkerGlobalScope.clearTimeout")}}
  • -
  • {{domxref("WindowOrWorkerGlobalScope.setInterval")}}
  • -
  • {{domxref("window.requestAnimationFrame")}}
  • -
diff --git a/files/ja/_redirects.txt b/files/ja/_redirects.txt index 05a124b25f..f129931200 100644 --- a/files/ja/_redirects.txt +++ b/files/ja/_redirects.txt @@ -1451,18 +1451,18 @@ /ja/docs/DOM/window.alert-redirect-1 /ja/docs/Web/API/Window/alert /ja/docs/DOM/window.applicationCache /ja/docs/Web/API/Window/applicationCache /ja/docs/DOM/window.arguments /ja/docs/orphaned/Working_with_windows_in_chrome_code -/ja/docs/DOM/window.atob /ja/docs/Web/API/WindowOrWorkerGlobalScope/atob -/ja/docs/DOM/window.atob-redirect-1 /ja/docs/Web/API/WindowOrWorkerGlobalScope/atob +/ja/docs/DOM/window.atob /ja/docs/Web/API/atob +/ja/docs/DOM/window.atob-redirect-1 /ja/docs/Web/API/atob /ja/docs/DOM/window.back /ja/docs/Web/API/Window/back /ja/docs/DOM/window.back-redirect-1 /ja/docs/Web/API/Window/back /ja/docs/DOM/window.blur /ja/docs/Web/API/Window/blur /ja/docs/DOM/window.blur-redirect-1 /ja/docs/Web/API/Window/blur -/ja/docs/DOM/window.btoa /ja/docs/Web/API/WindowOrWorkerGlobalScope/btoa -/ja/docs/DOM/window.btoa-redirect-1 /ja/docs/Web/API/WindowOrWorkerGlobalScope/btoa +/ja/docs/DOM/window.btoa /ja/docs/Web/API/btoa +/ja/docs/DOM/window.btoa-redirect-1 /ja/docs/Web/API/btoa /ja/docs/DOM/window.cancelAnimationFrame /ja/docs/Web/API/Window/cancelAnimationFrame /ja/docs/DOM/window.captureEvents /ja/docs/Web/API/Window/captureEvents -/ja/docs/DOM/window.clearInterval /ja/docs/Web/API/WindowOrWorkerGlobalScope/clearInterval -/ja/docs/DOM/window.clearTimeout /ja/docs/Web/API/WindowOrWorkerGlobalScope/clearTimeout +/ja/docs/DOM/window.clearInterval /ja/docs/Web/API/clearInterval +/ja/docs/DOM/window.clearTimeout /ja/docs/Web/API/clearTimeout /ja/docs/DOM/window.close /ja/docs/Web/API/Window/close /ja/docs/DOM/window.closed /ja/docs/Web/API/Window/closed /ja/docs/DOM/window.confirm /ja/docs/Web/API/Window/confirm @@ -1570,8 +1570,8 @@ /ja/docs/DOM/window.scrollY-redirect-1 /ja/docs/Web/API/Window/scrollY /ja/docs/DOM/window.scrollbars /ja/docs/Web/API/Window/scrollbars /ja/docs/DOM/window.self /ja/docs/Web/API/Window/self -/ja/docs/DOM/window.setInterval /ja/docs/Web/API/WindowOrWorkerGlobalScope/setInterval -/ja/docs/DOM/window.setTimeout /ja/docs/Web/API/WindowOrWorkerGlobalScope/setTimeout +/ja/docs/DOM/window.setInterval /ja/docs/Web/API/setInterval +/ja/docs/DOM/window.setTimeout /ja/docs/Web/API/setTimeout /ja/docs/DOM/window.showModalDialog /ja/docs/Web/API/Window/showModalDialog /ja/docs/DOM/window.sidebar /ja/docs/Web/API/Window/sidebar /ja/docs/DOM/window.sizeToContent /ja/docs/Web/API/Window/sizeToContent @@ -1684,13 +1684,13 @@ /ja/docs/DOM:window /ja/docs/Web/API/Window /ja/docs/DOM:window.alert /ja/docs/Web/API/Window/alert /ja/docs/DOM:window.applicationCache /ja/docs/Web/API/Window/applicationCache -/ja/docs/DOM:window.atob /ja/docs/Web/API/WindowOrWorkerGlobalScope/atob +/ja/docs/DOM:window.atob /ja/docs/Web/API/atob /ja/docs/DOM:window.back /ja/docs/Web/API/Window/back /ja/docs/DOM:window.blur /ja/docs/Web/API/Window/blur -/ja/docs/DOM:window.btoa /ja/docs/Web/API/WindowOrWorkerGlobalScope/btoa +/ja/docs/DOM:window.btoa /ja/docs/Web/API/btoa /ja/docs/DOM:window.captureEvents /ja/docs/Web/API/Window/captureEvents -/ja/docs/DOM:window.clearInterval /ja/docs/Web/API/WindowOrWorkerGlobalScope/clearInterval -/ja/docs/DOM:window.clearTimeout /ja/docs/Web/API/WindowOrWorkerGlobalScope/clearTimeout +/ja/docs/DOM:window.clearInterval /ja/docs/Web/API/clearInterval +/ja/docs/DOM:window.clearTimeout /ja/docs/Web/API/clearTimeout /ja/docs/DOM:window.close /ja/docs/Web/API/Window/close /ja/docs/DOM:window.closed /ja/docs/Web/API/Window/closed /ja/docs/DOM:window.confirm /ja/docs/Web/API/Window/confirm @@ -1784,8 +1784,8 @@ /ja/docs/DOM:window.scrollY /ja/docs/Web/API/Window/scrollY /ja/docs/DOM:window.scrollbars /ja/docs/Web/API/Window/scrollbars /ja/docs/DOM:window.self /ja/docs/Web/API/Window/self -/ja/docs/DOM:window.setInterval /ja/docs/Web/API/WindowOrWorkerGlobalScope/setInterval -/ja/docs/DOM:window.setTimeout /ja/docs/Web/API/WindowOrWorkerGlobalScope/setTimeout +/ja/docs/DOM:window.setInterval /ja/docs/Web/API/setInterval +/ja/docs/DOM:window.setTimeout /ja/docs/Web/API/setTimeout /ja/docs/DOM:window.showModalDialog /ja/docs/Web/API/Window/showModalDialog /ja/docs/DOM:window.sidebar /ja/docs/Web/API/Window/sidebar /ja/docs/DOM:window.sizeToContent /ja/docs/Web/API/Window/sizeToContent @@ -3103,7 +3103,7 @@ /ja/docs/Web/API/Geolocation.watchPosition /ja/docs/Web/API/Geolocation/watchPosition /ja/docs/Web/API/Geolocation/Using_geolocation /ja/docs/Web/API/Geolocation_API /ja/docs/Web/API/GlobalFetch /en-US/docs/Web/API/WindowOrWorkerGlobalScope -/ja/docs/Web/API/GlobalFetch/fetch /ja/docs/Web/API/WindowOrWorkerGlobalScope/fetch +/ja/docs/Web/API/GlobalFetch/fetch /ja/docs/Web/API/fetch /ja/docs/Web/API/HTMLFormElement.acceptCharset /ja/docs/Web/API/HTMLFormElement/acceptCharset /ja/docs/Web/API/HTMLFormElement.action /ja/docs/Web/API/HTMLFormElement/action /ja/docs/Web/API/HTMLFormElement.elements /ja/docs/Web/API/HTMLFormElement/elements @@ -3304,20 +3304,32 @@ /ja/docs/Web/API/Window/onreset /ja/docs/Web/API/GlobalEventHandlers/onreset /ja/docs/Web/API/Window/onresize /ja/docs/Web/API/GlobalEventHandlers/onresize /ja/docs/Web/API/Window/restore /ja/docs/Web/API/Window/moveTo -/ja/docs/Web/API/Window/setInterval /ja/docs/Web/API/WindowOrWorkerGlobalScope/setInterval -/ja/docs/Web/API/Window/setTimeout /ja/docs/Web/API/WindowOrWorkerGlobalScope/setTimeout +/ja/docs/Web/API/Window/setInterval /ja/docs/Web/API/setInterval +/ja/docs/Web/API/Window/setTimeout /ja/docs/Web/API/setTimeout /ja/docs/Web/API/Window/unescape /ja/docs/Web/JavaScript/Reference/Global_Objects/unescape /ja/docs/Web/API/Window/vrdisplaydisconnected_event /ja/docs/Web/API/Window/vrdisplaydisconnect_event /ja/docs/Web/API/WindowBase64 /ja/docs/Web/API/WindowOrWorkerGlobalScope /ja/docs/Web/API/WindowBase64/Base64_encoding_and_decoding /ja/docs/Glossary/Base64 -/ja/docs/Web/API/WindowBase64/atob /ja/docs/Web/API/WindowOrWorkerGlobalScope/atob -/ja/docs/Web/API/WindowBase64/btoa /ja/docs/Web/API/WindowOrWorkerGlobalScope/btoa +/ja/docs/Web/API/WindowBase64/atob /ja/docs/Web/API/atob +/ja/docs/Web/API/WindowBase64/btoa /ja/docs/Web/API/btoa +/ja/docs/Web/API/WindowOrWorkerGlobalScope/atob /ja/docs/Web/API/atob +/ja/docs/Web/API/WindowOrWorkerGlobalScope/btoa /ja/docs/Web/API/btoa +/ja/docs/Web/API/WindowOrWorkerGlobalScope/caches /ja/docs/Web/API/caches +/ja/docs/Web/API/WindowOrWorkerGlobalScope/clearInterval /ja/docs/Web/API/clearInterval +/ja/docs/Web/API/WindowOrWorkerGlobalScope/clearTimeout /ja/docs/Web/API/clearTimeout +/ja/docs/Web/API/WindowOrWorkerGlobalScope/createImageBitmap /ja/docs/Web/API/createImageBitmap +/ja/docs/Web/API/WindowOrWorkerGlobalScope/fetch /ja/docs/Web/API/fetch +/ja/docs/Web/API/WindowOrWorkerGlobalScope/indexedDB /ja/docs/Web/API/indexedDB +/ja/docs/Web/API/WindowOrWorkerGlobalScope/isSecureContext /ja/docs/Web/API/isSecureContext +/ja/docs/Web/API/WindowOrWorkerGlobalScope/origin /ja/docs/Web/API/origin +/ja/docs/Web/API/WindowOrWorkerGlobalScope/setInterval /ja/docs/Web/API/setInterval +/ja/docs/Web/API/WindowOrWorkerGlobalScope/setTimeout /ja/docs/Web/API/setTimeout /ja/docs/Web/API/WindowTimers /ja/docs/Web/API/WindowOrWorkerGlobalScope -/ja/docs/Web/API/WindowTimers/clearInterval /ja/docs/Web/API/WindowOrWorkerGlobalScope/clearInterval -/ja/docs/Web/API/WindowTimers/clearTimeout /ja/docs/Web/API/WindowOrWorkerGlobalScope/clearTimeout -/ja/docs/Web/API/WindowTimers/setInterval /ja/docs/Web/API/WindowOrWorkerGlobalScope/setInterval -/ja/docs/Web/API/WindowTimers/setTimeout /ja/docs/Web/API/WindowOrWorkerGlobalScope/setTimeout -/ja/docs/Web/API/WorkerGlobalScope/caches /ja/docs/Web/API/WindowOrWorkerGlobalScope/caches +/ja/docs/Web/API/WindowTimers/clearInterval /ja/docs/Web/API/clearInterval +/ja/docs/Web/API/WindowTimers/clearTimeout /ja/docs/Web/API/clearTimeout +/ja/docs/Web/API/WindowTimers/setInterval /ja/docs/Web/API/setInterval +/ja/docs/Web/API/WindowTimers/setTimeout /ja/docs/Web/API/setTimeout +/ja/docs/Web/API/WorkerGlobalScope/caches /ja/docs/Web/API/caches /ja/docs/Web/API/XMLHttpRequest/openRequest /ja/docs/orphaned/Web/API/XMLHttpRequest/openRequest /ja/docs/Web/API/XRHandedness /ja/docs/Web/API/XRInputSource/handedness /ja/docs/Web/API/XRReferenceSpaceEventInit /ja/docs/Web/API/XRReferenceSpaceEvent/XRReferenceSpaceEvent @@ -3432,14 +3444,14 @@ /ja/docs/Web/API/window.alert /ja/docs/Web/API/Window/alert /ja/docs/Web/API/window.applicationCache /ja/docs/Web/API/Window/applicationCache /ja/docs/Web/API/window.arguments /ja/docs/orphaned/Working_with_windows_in_chrome_code -/ja/docs/Web/API/window.atob /ja/docs/Web/API/WindowOrWorkerGlobalScope/atob +/ja/docs/Web/API/window.atob /ja/docs/Web/API/atob /ja/docs/Web/API/window.back /ja/docs/Web/API/Window/back /ja/docs/Web/API/window.blur /ja/docs/Web/API/Window/blur -/ja/docs/Web/API/window.btoa /ja/docs/Web/API/WindowOrWorkerGlobalScope/btoa +/ja/docs/Web/API/window.btoa /ja/docs/Web/API/btoa /ja/docs/Web/API/window.cancelAnimationFrame /ja/docs/Web/API/Window/cancelAnimationFrame /ja/docs/Web/API/window.captureEvents /ja/docs/Web/API/Window/captureEvents -/ja/docs/Web/API/window.clearInterval /ja/docs/Web/API/WindowOrWorkerGlobalScope/clearInterval -/ja/docs/Web/API/window.clearTimeout /ja/docs/Web/API/WindowOrWorkerGlobalScope/clearTimeout +/ja/docs/Web/API/window.clearInterval /ja/docs/Web/API/clearInterval +/ja/docs/Web/API/window.clearTimeout /ja/docs/Web/API/clearTimeout /ja/docs/Web/API/window.close /ja/docs/Web/API/Window/close /ja/docs/Web/API/window.closed /ja/docs/Web/API/Window/closed /ja/docs/Web/API/window.confirm /ja/docs/Web/API/Window/confirm @@ -3543,8 +3555,8 @@ /ja/docs/Web/API/window.scrollbars /ja/docs/Web/API/Window/scrollbars /ja/docs/Web/API/window.self /ja/docs/Web/API/Window/self /ja/docs/Web/API/window.setCursor /ja/docs/Web/API/Window/setCursor -/ja/docs/Web/API/window.setInterval /ja/docs/Web/API/WindowOrWorkerGlobalScope/setInterval -/ja/docs/Web/API/window.setTimeout /ja/docs/Web/API/WindowOrWorkerGlobalScope/setTimeout +/ja/docs/Web/API/window.setInterval /ja/docs/Web/API/setInterval +/ja/docs/Web/API/window.setTimeout /ja/docs/Web/API/setTimeout /ja/docs/Web/API/window.showModalDialog /ja/docs/Web/API/Window/showModalDialog /ja/docs/Web/API/window.sidebar /ja/docs/Web/API/Window/sidebar /ja/docs/Web/API/window.sizeToContent /ja/docs/Web/API/Window/sizeToContent @@ -4928,8 +4940,8 @@ /ja/docs/toSource /ja/docs/Web/JavaScript/Reference/Global_Objects/Object/toSource /ja/docs/toString /ja/docs/Web/JavaScript/Reference/Global_Objects/Object/toString /ja/docs/width /ja/docs/Web/CSS/width -/ja/docs/window.clearInterval /ja/docs/Web/API/WindowOrWorkerGlobalScope/clearInterval +/ja/docs/window.clearInterval /ja/docs/Web/API/clearInterval /ja/docs/window.screenY /ja/docs/Web/API/Window/screenY /ja/docs/window.scrollMaxY /ja/docs/Web/API/Window/scrollMaxY -/ja/docs/window.setInterval /ja/docs/Web/API/WindowOrWorkerGlobalScope/setInterval +/ja/docs/window.setInterval /ja/docs/Web/API/setInterval /ja/docs/メインページ /ja/docs/Web diff --git a/files/ja/_wikihistory.json b/files/ja/_wikihistory.json index 7d57f08678..1baf348d24 100644 --- a/files/ja/_wikihistory.json +++ b/files/ja/_wikihistory.json @@ -25420,136 +25420,6 @@ "kenrick95" ] }, - "Web/API/WindowOrWorkerGlobalScope/atob": { - "modified": "2020-10-15T21:16:19.721Z", - "contributors": [ - "mfuji09", - "fscholz", - "khalid32", - "ethertank", - "Potappo" - ] - }, - "Web/API/WindowOrWorkerGlobalScope/btoa": { - "modified": "2020-10-15T21:16:19.842Z", - "contributors": [ - "mfuji09", - "SphinxKnight", - "fscholz", - "khalid32", - "ethertank", - "Potappo" - ] - }, - "Web/API/WindowOrWorkerGlobalScope/caches": { - "modified": "2020-10-15T21:49:48.643Z", - "contributors": [ - "Wind1808", - "unarist", - "YuichiNukiyama" - ] - }, - "Web/API/WindowOrWorkerGlobalScope/clearInterval": { - "modified": "2019-03-23T23:49:51.484Z", - "contributors": [ - ".Hiroya", - "fscholz", - "khalid32", - "teoli", - "ethertank", - "Marsf", - "Mgjbot", - "Hfjapancom" - ] - }, - "Web/API/WindowOrWorkerGlobalScope/clearTimeout": { - "modified": "2020-10-15T21:16:17.778Z", - "contributors": [ - "mfuji09", - ".Hiroya", - "mushahiroyuki", - "fscholz", - "jsx", - "ethertank", - "Potappo" - ] - }, - "Web/API/WindowOrWorkerGlobalScope/createImageBitmap": { - "modified": "2020-10-15T22:34:31.000Z", - "contributors": [ - "silverskyvicto" - ] - }, - "Web/API/WindowOrWorkerGlobalScope/fetch": { - "modified": "2020-10-15T21:41:32.875Z", - "contributors": [ - "mfuji09", - "gladenjoy", - "Uemmra3", - "hamasaki", - "woodmix", - "fscholz", - "mdmss37", - "dskmori", - "aliceinwire", - "lv7777", - "Piroro-hs", - "chikoski" - ] - }, - "Web/API/WindowOrWorkerGlobalScope/indexedDB": { - "modified": "2019-03-23T22:01:21.947Z", - "contributors": [ - "Marsf" - ] - }, - "Web/API/WindowOrWorkerGlobalScope/isSecureContext": { - "modified": "2020-10-15T22:08:54.038Z", - "contributors": [ - "k-kuwahara" - ] - }, - "Web/API/WindowOrWorkerGlobalScope/origin": { - "modified": "2020-10-15T22:08:52.985Z", - "contributors": [ - "k-kuwahara" - ] - }, - "Web/API/WindowOrWorkerGlobalScope/setInterval": { - "modified": "2020-10-15T21:15:06.280Z", - "contributors": [ - "Potappo", - "yyss", - "mushahiroyuki", - "teoli", - "jsx", - "ethertank", - "Ceth", - "Shoot", - "Marsf", - "Okome", - "Taken", - "Mgjbot", - "Hfjapancom" - ] - }, - "Web/API/WindowOrWorkerGlobalScope/setTimeout": { - "modified": "2020-10-15T21:15:57.322Z", - "contributors": [ - "mfuji09", - "yyss", - "hamasaki", - "teoli", - "AshfaqHossain", - "ethertank", - "dextra", - "Ceth", - "Shoot", - "Marsf", - "Mgjbot", - "Hfjapancom" - ] - }, "Web/API/Worker": { "modified": "2020-10-15T21:37:11.821Z", "contributors": [ @@ -26246,6 +26116,60 @@ "Marsf" ] }, + "Web/API/atob": { + "modified": "2020-10-15T21:16:19.721Z", + "contributors": [ + "mfuji09", + "fscholz", + "khalid32", + "ethertank", + "Potappo" + ] + }, + "Web/API/btoa": { + "modified": "2020-10-15T21:16:19.842Z", + "contributors": [ + "mfuji09", + "SphinxKnight", + "fscholz", + "khalid32", + "ethertank", + "Potappo" + ] + }, + "Web/API/caches": { + "modified": "2020-10-15T21:49:48.643Z", + "contributors": [ + "Wind1808", + "unarist", + "YuichiNukiyama" + ] + }, + "Web/API/clearInterval": { + "modified": "2019-03-23T23:49:51.484Z", + "contributors": [ + ".Hiroya", + "fscholz", + "khalid32", + "teoli", + "ethertank", + "Marsf", + "Mgjbot", + "Hfjapancom" + ] + }, + "Web/API/clearTimeout": { + "modified": "2020-10-15T21:16:17.778Z", + "contributors": [ + "mfuji09", + ".Hiroya", + "mushahiroyuki", + "fscholz", + "jsx", + "ethertank", + "Potappo" + ] + }, "Web/API/console": { "modified": "2020-10-15T21:08:48.807Z", "contributors": [ @@ -26366,6 +26290,29 @@ "yyss" ] }, + "Web/API/createImageBitmap": { + "modified": "2020-10-15T22:34:31.000Z", + "contributors": [ + "silverskyvicto" + ] + }, + "Web/API/fetch": { + "modified": "2020-10-15T21:41:32.875Z", + "contributors": [ + "mfuji09", + "gladenjoy", + "Uemmra3", + "hamasaki", + "woodmix", + "fscholz", + "mdmss37", + "dskmori", + "aliceinwire", + "lv7777", + "Piroro-hs", + "chikoski" + ] + }, "Web/API/globalEventhandlers/onmousedown": { "modified": "2020-10-15T21:23:57.929Z", "contributors": [ @@ -26375,6 +26322,59 @@ "ethertank" ] }, + "Web/API/indexedDB": { + "modified": "2019-03-23T22:01:21.947Z", + "contributors": [ + "Marsf" + ] + }, + "Web/API/isSecureContext": { + "modified": "2020-10-15T22:08:54.038Z", + "contributors": [ + "k-kuwahara" + ] + }, + "Web/API/origin": { + "modified": "2020-10-15T22:08:52.985Z", + "contributors": [ + "k-kuwahara" + ] + }, + "Web/API/setInterval": { + "modified": "2020-10-15T21:15:06.280Z", + "contributors": [ + "Potappo", + "yyss", + "mushahiroyuki", + "teoli", + "jsx", + "ethertank", + "Ceth", + "Shoot", + "Marsf", + "Okome", + "Taken", + "Mgjbot", + "Hfjapancom" + ] + }, + "Web/API/setTimeout": { + "modified": "2020-10-15T21:15:57.322Z", + "contributors": [ + "mfuji09", + "yyss", + "hamasaki", + "teoli", + "AshfaqHossain", + "ethertank", + "dextra", + "Ceth", + "Shoot", + "Marsf", + "Mgjbot", + "Hfjapancom" + ] + }, "Web/API/treeWalker": { "modified": "2020-10-15T21:21:02.292Z", "contributors": [ 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")}}

+
+ +

関連情報

+ +
    +
  • data URI
  • +
  • {{domxref("WindowOrWorkerGlobalScope.atob","atob()")}}
  • +
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)
+
+ +
    +
  • intervalID: キャンセルする繰り返し動作の識別子。この ID は setInterval() の戻り値です。
  • +
+ +

+ +

{{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")}}

+ +

関連情報

+ +
    +
  • JavaScript timers
  • +
  • {{domxref("window.setTimeout")}}
  • +
  • {{domxref("window.setInterval")}}
  • +
  • {{domxref("window.clearTimeout")}}
  • +
  • {{domxref("window.requestAnimationFrame")}}
  • +
  • Daemons management
  • +
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")}}

+ +

関連情報

+ +
    +
  • {{domxref("WindowOrWorkerGlobalScope.setTimeout()")}}
  • +
  • {{domxref("WindowOrWorkerGlobalScope.setInterval()")}}
  • +
  • {{domxref("WindowOrWorkerGlobalScope.clearInterval()")}}
  • +
  • {{domxref("Window.requestAnimationFrame()")}}
  • +
  • Daemons management
  • +
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")}}

+ +

あわせて参照

+ +
    +
  • {{domxref("CanvasRenderingContext2D.drawImage()")}}
  • +
  • {{domxref("ImageData")}}
  • +
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")}}

+ +

関連情報

+ +
    +
  • Using IndexedDB
  • +
  • トランザクションの開始: {{domxref("IDBDatabase")}}
  • +
  • トランザクションの使用: {{domxref("IDBTransaction")}}
  • +
  • キーの範囲設定: {{domxref("IDBKeyRange")}}
  • +
  • データの取得と変更: {{domxref("IDBObjectStore")}}
  • +
  • カーソルの使用: {{domxref("IDBCursor")}}
  • +
  • 参照例: To-do Notifications (view example live.)
  • +
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")}}

+
+ +

関連情報

+ +
    +
  • JavaScript timers
  • +
  • {{domxref("WindowOrWorkerGlobalScope.setTimeout")}}
  • +
  • {{domxref("WindowOrWorkerGlobalScope.clearTimeout")}}
  • +
  • {{domxref("WindowOrWorkerGlobalScope.clearInterval")}}
  • +
  • {{domxref("window.requestAnimationFrame")}}
  • +
  • Daemons management
  • +
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 秒後に発効します。

+ +

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

+ +
    +
  • dom.min_tracking_timeout_value: 4
  • +
  • dom.min_tracking_background_timeout_value: 10000
  • +
  • dom.timeout.tracking_throttling_delay: 30000
  • +
+ +

タイムアウトの遅延

+ +

前出の "制限" に加えて、ページ内 (または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")}}

-
- -

関連情報

- -
    -
  • data URI
  • -
  • {{domxref("WindowOrWorkerGlobalScope.atob","atob()")}}
  • -
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)
-
- -
    -
  • intervalID: キャンセルする繰り返し動作の識別子。この ID は setInterval() の戻り値です。
  • -
- -

- -

{{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")}}

- -

関連情報

- -
    -
  • JavaScript timers
  • -
  • {{domxref("window.setTimeout")}}
  • -
  • {{domxref("window.setInterval")}}
  • -
  • {{domxref("window.clearTimeout")}}
  • -
  • {{domxref("window.requestAnimationFrame")}}
  • -
  • Daemons management
  • -
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")}}

- -

関連情報

- -
    -
  • {{domxref("WindowOrWorkerGlobalScope.setTimeout()")}}
  • -
  • {{domxref("WindowOrWorkerGlobalScope.setInterval()")}}
  • -
  • {{domxref("WindowOrWorkerGlobalScope.clearInterval()")}}
  • -
  • {{domxref("Window.requestAnimationFrame()")}}
  • -
  • Daemons management
  • -
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")}}

- -

あわせて参照

- -
    -
  • {{domxref("CanvasRenderingContext2D.drawImage()")}}
  • -
  • {{domxref("ImageData")}}
  • -
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")}}

- -

関連情報

- -
    -
  • Using IndexedDB
  • -
  • トランザクションの開始: {{domxref("IDBDatabase")}}
  • -
  • トランザクションの使用: {{domxref("IDBTransaction")}}
  • -
  • キーの範囲設定: {{domxref("IDBKeyRange")}}
  • -
  • データの取得と変更: {{domxref("IDBObjectStore")}}
  • -
  • カーソルの使用: {{domxref("IDBCursor")}}
  • -
  • 参照例: To-do Notifications (view example live.)
  • -
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")}}

-
- -

関連情報

- -
    -
  • JavaScript timers
  • -
  • {{domxref("WindowOrWorkerGlobalScope.setTimeout")}}
  • -
  • {{domxref("WindowOrWorkerGlobalScope.clearTimeout")}}
  • -
  • {{domxref("WindowOrWorkerGlobalScope.clearInterval")}}
  • -
  • {{domxref("window.requestAnimationFrame")}}
  • -
  • Daemons management
  • -
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 秒後に発効します。

- -

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

- -
    -
  • dom.min_tracking_timeout_value: 4
  • -
  • dom.min_tracking_background_timeout_value: 10000
  • -
  • dom.timeout.tracking_throttling_delay: 30000
  • -
- -

タイムアウトの遅延

- -

前出の "制限" に加えて、ページ内 (または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/ko/_redirects.txt b/files/ko/_redirects.txt index 98641a59c2..eca610565f 100644 --- a/files/ko/_redirects.txt +++ b/files/ko/_redirects.txt @@ -490,7 +490,8 @@ /ko/docs/Web/API/WebGL_API/Using_shaders_to_apply_color_in_WebGL /ko/docs/Web/API/WebGL_API/Tutorial/Using_shaders_to_apply_color_in_WebGL /ko/docs/Web/API/WebGL_API/Using_textures_in_WebGL /ko/docs/Web/API/WebGL_API/Tutorial/Using_textures_in_WebGL /ko/docs/Web/API/Web_Workers_API/basic_usage /ko/docs/Web/API/Web_Workers_API/Using_web_workers -/ko/docs/Web/API/WindowTimers/setTimeout /ko/docs/Web/API/WindowOrWorkerGlobalScope/setTimeout +/ko/docs/Web/API/WindowOrWorkerGlobalScope/setTimeout /ko/docs/Web/API/setTimeout +/ko/docs/Web/API/WindowTimers/setTimeout /ko/docs/Web/API/setTimeout /ko/docs/Web/API/XMLHttpRequest/timeout /ko/docs/Web/API/XMLHttpRequest/timeout_event /ko/docs/Web/API/document.importNode /ko/docs/Web/API/Document/importNode /ko/docs/Web/API/element-temp /ko/docs/Web/API/Element diff --git a/files/ko/_wikihistory.json b/files/ko/_wikihistory.json index 3d73c38255..58636a3a7f 100644 --- a/files/ko/_wikihistory.json +++ b/files/ko/_wikihistory.json @@ -7529,13 +7529,6 @@ "alattalatta" ] }, - "Web/API/WindowOrWorkerGlobalScope/setTimeout": { - "modified": "2019-03-23T22:22:22.449Z", - "contributors": [ - "DevJang", - "TroyTae" - ] - }, "Web/API/Worker": { "modified": "2020-10-15T21:47:12.252Z", "contributors": [ @@ -7646,6 +7639,13 @@ "junho85" ] }, + "Web/API/setTimeout": { + "modified": "2019-03-23T22:22:22.449Z", + "contributors": [ + "DevJang", + "TroyTae" + ] + }, "Web/Accessibility": { "modified": "2019-09-09T14:15:43.285Z", "contributors": [ diff --git a/files/ko/web/api/settimeout/index.html b/files/ko/web/api/settimeout/index.html new file mode 100644 index 0000000000..d093696bd0 --- /dev/null +++ b/files/ko/web/api/settimeout/index.html @@ -0,0 +1,363 @@ +--- +title: WindowTimers.setTimeout() +slug: Web/API/setTimeout +tags: + - setTimeout +translation_of: Web/API/WindowOrWorkerGlobalScope/setTimeout +original_slug: Web/API/WindowOrWorkerGlobalScope/setTimeout +--- +
{{APIRef("HTML DOM")}}
+ +

타이머가 만료된 뒤 함수나 지정된 코드를 실행하는 타이머를 설정합니다.

+ +

문법

+ +
var timeoutID = window.setTimeout(func[, delay, param1, param2, ...]);
+var timeoutID = window.setTimeout(code[, delay]);
+window.setTimeout(function, milliseconds);
+
+ +

매개변수

+ +
+
func
+
{{jsxref("function")}}이 타이머가 만료된 뒤 실행됩니다.
+
code
+
선택적 구문으로 함수 대신에 문자열을 넣을 수 있는데, 이것은 타이머가 만료된 뒤 해석되고 실행됩니다.
+ 이 구문은 {{jsxref("Global_Objects/eval", "eval()")}}을 사용하는 것과 같은 보안 위험성을 이유로 권장되지 않습니다.
+
delay {{optional_inline}}
+
타이머가 지정된 함수나 코드를 실행시키기 전에 기다려야할 ms(1000분의 1초) 단위의 시간입니다.
+ 만약 이 매개변수를 생략하면, 0이 값으로 사용됩니다. 실제 지연시간은 더 길어질 수 있습니다;
+ 아래 {{anch("Reasons for delays longer than specified")}}를 참고하세요.
+
param1, ..., paramN {{optional_inline}}
+
타이머가 만료되고 {{anch("func")}}에 전달되는 추가적인 매개변수들입니다.
+
+ +
+

Internet Explorer 9 이하에서는 함수에 추가적인 매개변수들을 전달하는 기능이 동작하지 않습니다.
+ 만약 브라우저에서 이 기능을 사용하고 싶다면, {{anch("polyfill")}}을 사용하세요. (Callback arguments를 봐주세요)

+
+ +

반환 값

+ +

반환되는 timeoutID는 숫자이고, setTimeout()을 호출하여 만들어진 타이머를 식별할 수 있는 0이 아닌 값 입니다;
+ 이 값은 타이머를 취소시키기 위해 {{domxref("WindowTimers.clearTimeout()")}}에 전달할 수도 있습니다.

+ +

setTimeout()과 {{domxref("WindowTimers.setInterval", "setInterval()")}}는 같은 ID 공간을 공유하기 때문에, clearTimeout()과 {{domxref("WindowTimers.clearInterval", "clearInterval()")}} 둘 중 어느 것을 사용해도 기술적으로 동일하게 동작합니다.
+ 하지만 명확성을 위해, 코드를 유지보수할 때 혼란을 피하기 위해 항상 일치시켜야 합니다.

+ +

예제

+ +

다음 예제는 웹 페이지에 2개의 간단한 버튼을 설정하고 setTimeout()과 clearTimeout()에 연결합니다.
+ 첫 번째 버튼이 눌려지면 2초 뒤에 호출되는 타임아웃이 설정되고 clearTimeout()에 사용되는 ID가 저장됩니다.
+ 두 번째 버튼을 누름으로써 당신은 선택적으로 이 타임아웃을 취소할 수 있습니다.

+ +

HTML

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

JavaScript

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

결과

+ +

{{EmbedLiveSample('Example')}}
+ clearTimeout() 예제도 봐주세요.

+ +

Polyfill

+ +

하나 이상의 매개변수를 콜백 함수에 넘겨야 하는데, setTimeout() 또는 setInterval()을 사용하여 추가적인 매개변수를 보내는 것을 브라우저에서 지원하지 않는다면(e.g. Internet Explorer 9 이하), HTML5 표준 매개변수 전달 기능을 사용 가능하게 하는 이 polyfill을 넣을 수 있습니다. 그저 아래 코드를 스크립트를 상단에 작성해주시면 됩니다.

+ +
/*\
+|*|
+|*|  임의의 매개변수를 자바스크립트 타이머의 콜백함수에 전달하기 위한 Polyfill (HTML5 표준 명세).
+|*|
+|*|  https://developer.mozilla.org/en-US/docs/DOM/window.setInterval
+|*|
+|*|  Syntax:
+|*|  var timeoutID = window.setTimeout(func, delay[, param1, param2, ...]);
+|*|  var timeoutID = window.setTimeout(code, delay);
+|*|  var intervalID = window.setInterval(func, delay[, param1, param2, ...]);
+|*|  var intervalID = window.setInterval(code, delay);
+|*|
+\*/
+
+(function() {
+  setTimeout(function(arg1) {
+    if (arg1 === 'test') {
+      // feature test is passed, no need for polyfill
+      return;
+    }
+    var __nativeST__ = window.setTimeout;
+    window.setTimeout = function(vCallback, nDelay /*, argumentToPass1, argumentToPass2, etc. */ ) {
+      var aArgs = Array.prototype.slice.call(arguments, 2);
+      return __nativeST__(vCallback instanceof Function ? function() {
+        vCallback.apply(null, aArgs);
+      } : vCallback, nDelay);
+    };
+  }, 0, 'test');
+
+  var interval = setInterval(function(arg1) {
+    clearInterval(interval);
+    if (arg1 === 'test') {
+      // feature test is passed, no need for polyfill
+      return;
+    }
+    var __nativeSI__ = window.setInterval;
+    window.setInterval = function(vCallback, nDelay /*, argumentToPass1, argumentToPass2, etc. */ ) {
+      var aArgs = Array.prototype.slice.call(arguments, 2);
+      return __nativeSI__(vCallback instanceof Function ? function() {
+        vCallback.apply(null, aArgs);
+      } : vCallback, nDelay);
+    };
+  }, 0, 'test');
+}())
+
+ +

IE

+ +

IE9 이하를 포함하는 모든 모바일/데스크톱 브라우저에서 자바스크립트를 남용하지 않는 완벽한 해결책으로 , 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]-->
+
+ +

예시

+ +

다른 해결책으로는 익명 함수를 callback으로 호출하여 사용할 수 있으나, 이 방법은 비용이 더 비쌉니다.

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

위 예제는 arrow function으로도 작성하실 수 있습니다.

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

다른 하나는 function's bind를 이용하는 것 입니다.

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

"this" 문제

+ +

setTimeout()에 매개변수(혹은 다른 함수)를 전달할 때, 당신의 기대와는 다르게 this의 값이 호출될 것이다. 해당 이슈에 대한 자세한 사항은 JavaScript reference를 참고해주세요.

+ +

설명

+ +

setTimeout()에 의해 실행된 코드는 별도의 실행 컨텍스트에서 setTimeout이 호출된 함수로 호출됩니다.  호출된 함수에 대해서는 this 키워드를 설정하는 일반적인 규칙이 적용되며, this를 설정 혹은 할당하지 않은 경우, non-strict 모드에서 전역(혹은 window) 객체, strict모드에서 undefined를 기본 값으로 합니다. 다음 예제를 봐주세요: 

+ +
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 호출될 때, this는 myArray로 설정되므로, 함수 내에서의 this[속성]은 myArray[속성]와 같습니다. 하지만, 다음 예제를 보면:

+ +
setTimeout(myArray.myMethod, 1000); // 1초 뒤 "[Window 객체]" 출력
+setTimeout(myArray.myMethod, 1500, "1"); // 1.5초 뒤 "undefined" 출력
+ +

myArray.myMethod 함수는 setTimeout에 전달되고, 호출될 때 this는 설정되어 있지 않아 window 객체를 기본값으로 합니다. forEach, reduce 등 Array 메서드 같이 this를 매개변수로 넘길 수 있는 옵션 또한 없습니다. 그리고 아래에서 보다시피, call 사용해 this를 설정하는 것도 동작하지 않습니다.

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

가능한 해결책

+ +

일반적인 해결책은 this 설정이 필요한 곳을 함수로 감싸는 것(Wrapper Function) 입니다:

+ +
setTimeout(function(){myArray.myMethod()}, 2000); // 2초 뒤"zero,one,two" 출력
+setTimeout(function(){myArray.myMethod('1')}, 2500); // 2.5초 뒤"one" 출력
+ +

화살표 함수(Arrow Function) 역시 가능한 대안입니다:

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

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 표준 또한 가능하게 합니다.
+ +

새로운 기능 테스트:

+ +
myArray = ["zero", "one", "two"];
+myArray.myMethod = function (sProperty) {
+    alert(arguments.length > 0 ? this[sProperty] : this);
+};
+
+setTimeout(alert, 1500, "Hello world!"); // the standard use of setTimeout and setInterval is preserved, but...
+setTimeout.call(myArray, myArray.myMethod, 2000); // prints "zero,one,two" after 2 seconds
+setTimeout.call(myArray, myArray.myMethod, 2500, 2); // prints "two" after 2.5 seconds
+
+ +
JavaScript 1.8.5은 주어진 함수에 대한 모든 호출의 this 값을 설정하기 위한 Function.prototype.bind() 메서드를 도입하였습니다. 이렇게 하면 wrapper 함수를 사용하지 않고 콜백에 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, 1000); // still prints "zero,one,two" after 1 second because of the binding
+setTimeout(myBoundMethod, 1500, "1"); // prints "one" after 1.5 seconds
+
+ +

참고

+ +

Timeout은 {{domxref("WindowOrWorkerGlobalScope.clearTimeout()")}}을 사용하면 취소됩니다. 함수를 반복해서 호출해야 한다면 (e.g., N 밀리초마다), {{domxref("WindowOrWorkerGlobalScope.setInterval()")}} 사용을 고려해보세요.

+ +

setTimeout()을 호출한 쓰레드가 종료될 때까지 함수나 코드 조각이 실행될 수 없다는 점에 유의해야합니다. 예를들어:

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

콘솔에 이렇게 쓰여질겁니다:

+ +
After setTimeout
+foo has been called
+ +

그 이유는 setTimeout가 지연시간 0으로 호출되었지만, queue에 배치되어 다음 기회에 실행되도록 예정되기 때문입니다. 현재 실행중인 코드는 queue에 있는 함수들이 실행되기 전에 완료되고, 실행 순서가 예상과 다를 수 있습니다.

+ +

문자열을 넘길경우

+ +

 setTimeout() 함수대신 문자열을 넘기면 eval 사용했을 때와 같은 위험성을 가집니다.

+ +
// 권장
+window.setTimeout(function() {
+    alert("Hello World!");
+}, 500);
+
+// 비권장
+window.setTimeout("alert('Hello World!');", 500);
+
+ +

setTimeout에 전달된 문자열은 전역 context에서 해석하므로, setTimeout()이 호출된 로컬 context의 Symbol은 문자열이 코드로 해석될 때 사용할 수 없습니다.

+ +

지정된 것보다 더 오래 지연되는 이유

+ +

타임아웃이 예상보다 더 늦게까지 지연되는 데는 여러가지 이유가 있습니다. 이 문단에서는 일반적인 이유에 대해서 설명합니다.

+ +

중첩된 타임아웃이 4ms 이하일 경우

+ +

역사적으로 브라우저들은 setTimeout() "clamping"을 구현했습니다: "최소 지연" 한계보다 작은 지연을 가진 setTimeout() 호출은 최소 지연을 사용하도록 강제됩니다.

+ +

실제로, 4ms는 HTML5 스펙에 명시되어 있고 2010년 이후에 출시된 브라우저들은 일관성을 유지하고 있습니다. {{geckoRelease("5.0")}} 이전에 출시된 브라우저들은, 타임아웃(중첩 5이상)의 최소 지연시간은 10ms였습니다.

+ +

최신 브라우저에서 0ms 타임아웃을 구현하려면, 이곳에 설명된 {{domxref("window.postMessage()")}}를 사용할 수 있습니다.

+ +

비활성 탭에서 타임아웃이1000ms에 여러 번 일어날 경우

+ +

부하와 배터리 사용양을 줄이기 위해서, 비활성화 탭들에서 타임아웃이 1초에 여러번 일어나지 않도록 "clamping" 됩니다.

+ +

Firefox는 5버전부터 이 동작을 구현했습니다. ({{bug(633421)}}참고, 1000ms 상수는  dom.min_background_timeout_value 설정을 통해 수정할 수 있습니다)
+ Chrome은  11버전부터 구현했습니다 (crbug.com/66078).

+ +

Android용 Firefox는 {{bug(736602)}} 이후 버전 14부터 백그라운드 탭에 15분의 타임아웃을 사용하고, 완전히 unload도 할 수 있습니다.

+ +

타임아웃 지연

+ +

"clamping"과 더불어, 타임아웃은 다른 작업들로 인해 바쁜 페이지에서 늦게 실행될 수 있습니다.

+ +

최대 지연 값

+ +

Internet Explorer, Chrome, Safari, and Firefox 포함하는 브라우저들은 내부적으로 32-bit 부호있는 정수로 지연 값을 저장합니다. 이로 인해 2147483647보다 더 큰 지연을 사용할 때 정수 오버플로우가 발생하여, 타임아웃이 즉시 실행됩니다.

+ +

사양

+ + + + + + + + + + + + + + +
사양상태주석
{{SpecName("HTML WHATWG", "webappapis.html#dom-settimeout", "WindowTimers.setTimeout()")}}{{Spec2("HTML WHATWG")}}Initial definition (DOM Level 0)
+ +

지원 브라우저

+ +

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

+ +

더 알아보기

+ + diff --git a/files/ko/web/api/windoworworkerglobalscope/settimeout/index.html b/files/ko/web/api/windoworworkerglobalscope/settimeout/index.html deleted file mode 100644 index 1b7c4c6a78..0000000000 --- a/files/ko/web/api/windoworworkerglobalscope/settimeout/index.html +++ /dev/null @@ -1,363 +0,0 @@ ---- -title: WindowTimers.setTimeout() -slug: Web/API/WindowOrWorkerGlobalScope/setTimeout -tags: - - setTimeout -translation_of: Web/API/WindowOrWorkerGlobalScope/setTimeout -original_slug: Web/API/WindowTimers/setTimeout ---- -
{{APIRef("HTML DOM")}}
- -

타이머가 만료된 뒤 함수나 지정된 코드를 실행하는 타이머를 설정합니다.

- -

문법

- -
var timeoutID = window.setTimeout(func[, delay, param1, param2, ...]);
-var timeoutID = window.setTimeout(code[, delay]);
-window.setTimeout(function, milliseconds);
-
- -

매개변수

- -
-
func
-
{{jsxref("function")}}이 타이머가 만료된 뒤 실행됩니다.
-
code
-
선택적 구문으로 함수 대신에 문자열을 넣을 수 있는데, 이것은 타이머가 만료된 뒤 해석되고 실행됩니다.
- 이 구문은 {{jsxref("Global_Objects/eval", "eval()")}}을 사용하는 것과 같은 보안 위험성을 이유로 권장되지 않습니다.
-
delay {{optional_inline}}
-
타이머가 지정된 함수나 코드를 실행시키기 전에 기다려야할 ms(1000분의 1초) 단위의 시간입니다.
- 만약 이 매개변수를 생략하면, 0이 값으로 사용됩니다. 실제 지연시간은 더 길어질 수 있습니다;
- 아래 {{anch("Reasons for delays longer than specified")}}를 참고하세요.
-
param1, ..., paramN {{optional_inline}}
-
타이머가 만료되고 {{anch("func")}}에 전달되는 추가적인 매개변수들입니다.
-
- -
-

Internet Explorer 9 이하에서는 함수에 추가적인 매개변수들을 전달하는 기능이 동작하지 않습니다.
- 만약 브라우저에서 이 기능을 사용하고 싶다면, {{anch("polyfill")}}을 사용하세요. (Callback arguments를 봐주세요)

-
- -

반환 값

- -

반환되는 timeoutID는 숫자이고, setTimeout()을 호출하여 만들어진 타이머를 식별할 수 있는 0이 아닌 값 입니다;
- 이 값은 타이머를 취소시키기 위해 {{domxref("WindowTimers.clearTimeout()")}}에 전달할 수도 있습니다.

- -

setTimeout()과 {{domxref("WindowTimers.setInterval", "setInterval()")}}는 같은 ID 공간을 공유하기 때문에, clearTimeout()과 {{domxref("WindowTimers.clearInterval", "clearInterval()")}} 둘 중 어느 것을 사용해도 기술적으로 동일하게 동작합니다.
- 하지만 명확성을 위해, 코드를 유지보수할 때 혼란을 피하기 위해 항상 일치시켜야 합니다.

- -

예제

- -

다음 예제는 웹 페이지에 2개의 간단한 버튼을 설정하고 setTimeout()과 clearTimeout()에 연결합니다.
- 첫 번째 버튼이 눌려지면 2초 뒤에 호출되는 타임아웃이 설정되고 clearTimeout()에 사용되는 ID가 저장됩니다.
- 두 번째 버튼을 누름으로써 당신은 선택적으로 이 타임아웃을 취소할 수 있습니다.

- -

HTML

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

JavaScript

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

결과

- -

{{EmbedLiveSample('Example')}}
- clearTimeout() 예제도 봐주세요.

- -

Polyfill

- -

하나 이상의 매개변수를 콜백 함수에 넘겨야 하는데, setTimeout() 또는 setInterval()을 사용하여 추가적인 매개변수를 보내는 것을 브라우저에서 지원하지 않는다면(e.g. Internet Explorer 9 이하), HTML5 표준 매개변수 전달 기능을 사용 가능하게 하는 이 polyfill을 넣을 수 있습니다. 그저 아래 코드를 스크립트를 상단에 작성해주시면 됩니다.

- -
/*\
-|*|
-|*|  임의의 매개변수를 자바스크립트 타이머의 콜백함수에 전달하기 위한 Polyfill (HTML5 표준 명세).
-|*|
-|*|  https://developer.mozilla.org/en-US/docs/DOM/window.setInterval
-|*|
-|*|  Syntax:
-|*|  var timeoutID = window.setTimeout(func, delay[, param1, param2, ...]);
-|*|  var timeoutID = window.setTimeout(code, delay);
-|*|  var intervalID = window.setInterval(func, delay[, param1, param2, ...]);
-|*|  var intervalID = window.setInterval(code, delay);
-|*|
-\*/
-
-(function() {
-  setTimeout(function(arg1) {
-    if (arg1 === 'test') {
-      // feature test is passed, no need for polyfill
-      return;
-    }
-    var __nativeST__ = window.setTimeout;
-    window.setTimeout = function(vCallback, nDelay /*, argumentToPass1, argumentToPass2, etc. */ ) {
-      var aArgs = Array.prototype.slice.call(arguments, 2);
-      return __nativeST__(vCallback instanceof Function ? function() {
-        vCallback.apply(null, aArgs);
-      } : vCallback, nDelay);
-    };
-  }, 0, 'test');
-
-  var interval = setInterval(function(arg1) {
-    clearInterval(interval);
-    if (arg1 === 'test') {
-      // feature test is passed, no need for polyfill
-      return;
-    }
-    var __nativeSI__ = window.setInterval;
-    window.setInterval = function(vCallback, nDelay /*, argumentToPass1, argumentToPass2, etc. */ ) {
-      var aArgs = Array.prototype.slice.call(arguments, 2);
-      return __nativeSI__(vCallback instanceof Function ? function() {
-        vCallback.apply(null, aArgs);
-      } : vCallback, nDelay);
-    };
-  }, 0, 'test');
-}())
-
- -

IE

- -

IE9 이하를 포함하는 모든 모바일/데스크톱 브라우저에서 자바스크립트를 남용하지 않는 완벽한 해결책으로 , 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]-->
-
- -

예시

- -

다른 해결책으로는 익명 함수를 callback으로 호출하여 사용할 수 있으나, 이 방법은 비용이 더 비쌉니다.

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

위 예제는 arrow function으로도 작성하실 수 있습니다.

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

다른 하나는 function's bind를 이용하는 것 입니다.

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

"this" 문제

- -

setTimeout()에 매개변수(혹은 다른 함수)를 전달할 때, 당신의 기대와는 다르게 this의 값이 호출될 것이다. 해당 이슈에 대한 자세한 사항은 JavaScript reference를 참고해주세요.

- -

설명

- -

setTimeout()에 의해 실행된 코드는 별도의 실행 컨텍스트에서 setTimeout이 호출된 함수로 호출됩니다.  호출된 함수에 대해서는 this 키워드를 설정하는 일반적인 규칙이 적용되며, this를 설정 혹은 할당하지 않은 경우, non-strict 모드에서 전역(혹은 window) 객체, strict모드에서 undefined를 기본 값으로 합니다. 다음 예제를 봐주세요: 

- -
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 호출될 때, this는 myArray로 설정되므로, 함수 내에서의 this[속성]은 myArray[속성]와 같습니다. 하지만, 다음 예제를 보면:

- -
setTimeout(myArray.myMethod, 1000); // 1초 뒤 "[Window 객체]" 출력
-setTimeout(myArray.myMethod, 1500, "1"); // 1.5초 뒤 "undefined" 출력
- -

myArray.myMethod 함수는 setTimeout에 전달되고, 호출될 때 this는 설정되어 있지 않아 window 객체를 기본값으로 합니다. forEach, reduce 등 Array 메서드 같이 this를 매개변수로 넘길 수 있는 옵션 또한 없습니다. 그리고 아래에서 보다시피, call 사용해 this를 설정하는 것도 동작하지 않습니다.

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

가능한 해결책

- -

일반적인 해결책은 this 설정이 필요한 곳을 함수로 감싸는 것(Wrapper Function) 입니다:

- -
setTimeout(function(){myArray.myMethod()}, 2000); // 2초 뒤"zero,one,two" 출력
-setTimeout(function(){myArray.myMethod('1')}, 2500); // 2.5초 뒤"one" 출력
- -

화살표 함수(Arrow Function) 역시 가능한 대안입니다:

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

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 표준 또한 가능하게 합니다.
- -

새로운 기능 테스트:

- -
myArray = ["zero", "one", "two"];
-myArray.myMethod = function (sProperty) {
-    alert(arguments.length > 0 ? this[sProperty] : this);
-};
-
-setTimeout(alert, 1500, "Hello world!"); // the standard use of setTimeout and setInterval is preserved, but...
-setTimeout.call(myArray, myArray.myMethod, 2000); // prints "zero,one,two" after 2 seconds
-setTimeout.call(myArray, myArray.myMethod, 2500, 2); // prints "two" after 2.5 seconds
-
- -
JavaScript 1.8.5은 주어진 함수에 대한 모든 호출의 this 값을 설정하기 위한 Function.prototype.bind() 메서드를 도입하였습니다. 이렇게 하면 wrapper 함수를 사용하지 않고 콜백에 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, 1000); // still prints "zero,one,two" after 1 second because of the binding
-setTimeout(myBoundMethod, 1500, "1"); // prints "one" after 1.5 seconds
-
- -

참고

- -

Timeout은 {{domxref("WindowOrWorkerGlobalScope.clearTimeout()")}}을 사용하면 취소됩니다. 함수를 반복해서 호출해야 한다면 (e.g., N 밀리초마다), {{domxref("WindowOrWorkerGlobalScope.setInterval()")}} 사용을 고려해보세요.

- -

setTimeout()을 호출한 쓰레드가 종료될 때까지 함수나 코드 조각이 실행될 수 없다는 점에 유의해야합니다. 예를들어:

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

콘솔에 이렇게 쓰여질겁니다:

- -
After setTimeout
-foo has been called
- -

그 이유는 setTimeout가 지연시간 0으로 호출되었지만, queue에 배치되어 다음 기회에 실행되도록 예정되기 때문입니다. 현재 실행중인 코드는 queue에 있는 함수들이 실행되기 전에 완료되고, 실행 순서가 예상과 다를 수 있습니다.

- -

문자열을 넘길경우

- -

 setTimeout() 함수대신 문자열을 넘기면 eval 사용했을 때와 같은 위험성을 가집니다.

- -
// 권장
-window.setTimeout(function() {
-    alert("Hello World!");
-}, 500);
-
-// 비권장
-window.setTimeout("alert('Hello World!');", 500);
-
- -

setTimeout에 전달된 문자열은 전역 context에서 해석하므로, setTimeout()이 호출된 로컬 context의 Symbol은 문자열이 코드로 해석될 때 사용할 수 없습니다.

- -

지정된 것보다 더 오래 지연되는 이유

- -

타임아웃이 예상보다 더 늦게까지 지연되는 데는 여러가지 이유가 있습니다. 이 문단에서는 일반적인 이유에 대해서 설명합니다.

- -

중첩된 타임아웃이 4ms 이하일 경우

- -

역사적으로 브라우저들은 setTimeout() "clamping"을 구현했습니다: "최소 지연" 한계보다 작은 지연을 가진 setTimeout() 호출은 최소 지연을 사용하도록 강제됩니다.

- -

실제로, 4ms는 HTML5 스펙에 명시되어 있고 2010년 이후에 출시된 브라우저들은 일관성을 유지하고 있습니다. {{geckoRelease("5.0")}} 이전에 출시된 브라우저들은, 타임아웃(중첩 5이상)의 최소 지연시간은 10ms였습니다.

- -

최신 브라우저에서 0ms 타임아웃을 구현하려면, 이곳에 설명된 {{domxref("window.postMessage()")}}를 사용할 수 있습니다.

- -

비활성 탭에서 타임아웃이1000ms에 여러 번 일어날 경우

- -

부하와 배터리 사용양을 줄이기 위해서, 비활성화 탭들에서 타임아웃이 1초에 여러번 일어나지 않도록 "clamping" 됩니다.

- -

Firefox는 5버전부터 이 동작을 구현했습니다. ({{bug(633421)}}참고, 1000ms 상수는  dom.min_background_timeout_value 설정을 통해 수정할 수 있습니다)
- Chrome은  11버전부터 구현했습니다 (crbug.com/66078).

- -

Android용 Firefox는 {{bug(736602)}} 이후 버전 14부터 백그라운드 탭에 15분의 타임아웃을 사용하고, 완전히 unload도 할 수 있습니다.

- -

타임아웃 지연

- -

"clamping"과 더불어, 타임아웃은 다른 작업들로 인해 바쁜 페이지에서 늦게 실행될 수 있습니다.

- -

최대 지연 값

- -

Internet Explorer, Chrome, Safari, and Firefox 포함하는 브라우저들은 내부적으로 32-bit 부호있는 정수로 지연 값을 저장합니다. 이로 인해 2147483647보다 더 큰 지연을 사용할 때 정수 오버플로우가 발생하여, 타임아웃이 즉시 실행됩니다.

- -

사양

- - - - - - - - - - - - - - -
사양상태주석
{{SpecName("HTML WHATWG", "webappapis.html#dom-settimeout", "WindowTimers.setTimeout()")}}{{Spec2("HTML WHATWG")}}Initial definition (DOM Level 0)
- -

지원 브라우저

- -

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

- -

더 알아보기

- - diff --git a/files/pl/_redirects.txt b/files/pl/_redirects.txt index 22537b5644..82c05c3816 100644 --- a/files/pl/_redirects.txt +++ b/files/pl/_redirects.txt @@ -439,8 +439,8 @@ /pl/docs/DOM/table.tHead /pl/docs/Web/API/HTMLTableElement/tHead /pl/docs/DOM/window /pl/docs/Web/API/Window /pl/docs/DOM/window.alert /pl/docs/Web/API/Window/alert -/pl/docs/DOM/window.clearInterval /pl/docs/Web/API/WindowOrWorkerGlobalScope/clearInterval -/pl/docs/DOM/window.clearTimeout /pl/docs/Web/API/WindowOrWorkerGlobalScope/clearTimeout +/pl/docs/DOM/window.clearInterval /pl/docs/Web/API/clearInterval +/pl/docs/DOM/window.clearTimeout /pl/docs/Web/API/clearTimeout /pl/docs/DOM/window.closed /pl/docs/Web/API/Window/closed /pl/docs/DOM/window.controllers /pl/docs/Web/API/Window/controllers /pl/docs/DOM/window.crypto /pl/docs/Web/API/Window/crypto @@ -480,8 +480,8 @@ /pl/docs/DOM/window.scrollByLines /pl/docs/Web/API/Window/scrollByLines /pl/docs/DOM/window.scrollByPages /pl/docs/Web/API/Window/scrollByPages /pl/docs/DOM/window.scrollTo /pl/docs/Web/API/Window/scrollTo -/pl/docs/DOM/window.setInterval /pl/docs/Web/API/WindowOrWorkerGlobalScope/setInterval -/pl/docs/DOM/window.setTimeout /pl/docs/Web/API/WindowOrWorkerGlobalScope/setTimeout +/pl/docs/DOM/window.setInterval /pl/docs/Web/API/setInterval +/pl/docs/DOM/window.setTimeout /pl/docs/Web/API/setTimeout /pl/docs/DOM:CSS /pl/docs/Web/CSS/Reference /pl/docs/DOM:Selection /pl/docs/Web/API/Selection /pl/docs/DOM:Selection:addRange /pl/docs/Web/API/Selection/addRange @@ -712,8 +712,8 @@ /pl/docs/DOM:window.scrollByLines /pl/docs/Web/API/Window/scrollByLines /pl/docs/DOM:window.scrollByPages /pl/docs/Web/API/Window/scrollByPages /pl/docs/DOM:window.scrollTo /pl/docs/Web/API/Window/scrollTo -/pl/docs/DOM:window.setInterval /pl/docs/Web/API/WindowOrWorkerGlobalScope/setInterval -/pl/docs/DOM:window.setTimeout /pl/docs/Web/API/WindowOrWorkerGlobalScope/setTimeout +/pl/docs/DOM:window.setInterval /pl/docs/Web/API/setInterval +/pl/docs/DOM:window.setTimeout /pl/docs/Web/API/setTimeout /pl/docs/Dodatki_w_Mozilli_-_FAQ(link) https://addons.mozilla.org/faq.php /pl/docs/Dokumentacja_CSS /pl/docs/Web/CSS/Reference /pl/docs/Dokumentacja_CSS/Rozszerzenia_Mozilli /pl/docs/Web/CSS/Mozilla_Extensions @@ -1501,16 +1501,22 @@ /pl/docs/Web/API/Stylesheet/insertRule /pl/docs/Web/API/CSSStyleSheet/insertRule /pl/docs/Web/API/UIEvent/pageX /pl/docs/Web/API/MouseEvent/pageX /pl/docs/Web/API/UIEvent/pageY /pl/docs/Web/API/MouseEvent/pageY -/pl/docs/Web/API/Window/clearInterval /pl/docs/Web/API/WindowOrWorkerGlobalScope/clearInterval -/pl/docs/Web/API/Window/clearTimeout /pl/docs/Web/API/WindowOrWorkerGlobalScope/clearTimeout +/pl/docs/Web/API/Window/clearInterval /pl/docs/Web/API/clearInterval +/pl/docs/Web/API/Window/clearTimeout /pl/docs/Web/API/clearTimeout /pl/docs/Web/API/Window/onload /pl/docs/Web/API/GlobalEventHandlers/onload -/pl/docs/Web/API/Window/setInterval /pl/docs/Web/API/WindowOrWorkerGlobalScope/setInterval -/pl/docs/Web/API/Window/setTimeout /pl/docs/Web/API/WindowOrWorkerGlobalScope/setTimeout +/pl/docs/Web/API/Window/setInterval /pl/docs/Web/API/setInterval +/pl/docs/Web/API/Window/setTimeout /pl/docs/Web/API/setTimeout /pl/docs/Web/API/WindowBase64 /pl/docs/Web/API/WindowOrWorkerGlobalScope -/pl/docs/Web/API/WindowBase64.atob /pl/docs/Web/API/WindowOrWorkerGlobalScope/atob -/pl/docs/Web/API/WindowBase64.btoa /pl/docs/Web/API/WindowOrWorkerGlobalScope/btoa -/pl/docs/Web/API/WindowBase64/atob /pl/docs/Web/API/WindowOrWorkerGlobalScope/atob -/pl/docs/Web/API/WindowBase64/btoa /pl/docs/Web/API/WindowOrWorkerGlobalScope/btoa +/pl/docs/Web/API/WindowBase64.atob /pl/docs/Web/API/atob +/pl/docs/Web/API/WindowBase64.btoa /pl/docs/Web/API/btoa +/pl/docs/Web/API/WindowBase64/atob /pl/docs/Web/API/atob +/pl/docs/Web/API/WindowBase64/btoa /pl/docs/Web/API/btoa +/pl/docs/Web/API/WindowOrWorkerGlobalScope/atob /pl/docs/Web/API/atob +/pl/docs/Web/API/WindowOrWorkerGlobalScope/btoa /pl/docs/Web/API/btoa +/pl/docs/Web/API/WindowOrWorkerGlobalScope/clearInterval /pl/docs/Web/API/clearInterval +/pl/docs/Web/API/WindowOrWorkerGlobalScope/clearTimeout /pl/docs/Web/API/clearTimeout +/pl/docs/Web/API/WindowOrWorkerGlobalScope/setInterval /pl/docs/Web/API/setInterval +/pl/docs/Web/API/WindowOrWorkerGlobalScope/setTimeout /pl/docs/Web/API/setTimeout /pl/docs/Web/API/Zdarzenia_dotykowe /pl/docs/Web/API/Touch_events /pl/docs/Web/API/powiadomienie /pl/docs/Web/API/Notification /pl/docs/Web/Accessibility/ARIA/Aplikacje_internetowe_i_ARIA_FAQ /pl/docs/Web/Accessibility/ARIA/Web_applications_and_ARIA_FAQ diff --git a/files/pl/_wikihistory.json b/files/pl/_wikihistory.json index e9f31f291a..331ae74307 100644 --- a/files/pl/_wikihistory.json +++ b/files/pl/_wikihistory.json @@ -3881,21 +3881,33 @@ "teoli" ] }, - "Web/API/WindowOrWorkerGlobalScope/atob": { + "Web/API/XMLHttpRequest": { + "modified": "2019-03-23T23:55:55.505Z", + "contributors": [ + "fnevgeny", + "Flaneur", + "Bedi", + "Mgjbot", + "Ptak82", + "Ziombka", + "gandalf" + ] + }, + "Web/API/atob": { "modified": "2019-03-23T23:09:12.984Z", "contributors": [ "teoli", "Eltu" ] }, - "Web/API/WindowOrWorkerGlobalScope/btoa": { + "Web/API/btoa": { "modified": "2019-03-23T23:09:14.333Z", "contributors": [ "teoli", "Eltu" ] }, - "Web/API/WindowOrWorkerGlobalScope/clearInterval": { + "Web/API/clearInterval": { "modified": "2019-03-24T00:10:08.372Z", "contributors": [ "teoli", @@ -3904,7 +3916,7 @@ "qfel13" ] }, - "Web/API/WindowOrWorkerGlobalScope/clearTimeout": { + "Web/API/clearTimeout": { "modified": "2019-03-24T00:10:09.180Z", "contributors": [ "teoli", @@ -3912,7 +3924,7 @@ "qfel13" ] }, - "Web/API/WindowOrWorkerGlobalScope/setInterval": { + "Web/API/setInterval": { "modified": "2019-03-24T00:10:09.408Z", "contributors": [ "Bajdzis", @@ -3923,7 +3935,7 @@ "Jan Dudek" ] }, - "Web/API/WindowOrWorkerGlobalScope/setTimeout": { + "Web/API/setTimeout": { "modified": "2019-03-24T00:10:06.439Z", "contributors": [ "teoli", @@ -3934,18 +3946,6 @@ "Jan Dudek" ] }, - "Web/API/XMLHttpRequest": { - "modified": "2019-03-23T23:55:55.505Z", - "contributors": [ - "fnevgeny", - "Flaneur", - "Bedi", - "Mgjbot", - "Ptak82", - "Ziombka", - "gandalf" - ] - }, "Web/Accessibility": { "modified": "2019-09-09T14:17:31.130Z", "contributors": [ diff --git a/files/pl/web/api/atob/index.html b/files/pl/web/api/atob/index.html new file mode 100644 index 0000000000..9e589fdfae --- /dev/null +++ b/files/pl/web/api/atob/index.html @@ -0,0 +1,105 @@ +--- +title: WindowBase64.atob() +slug: Web/API/atob +tags: + - API + - Base-64 + - Base64 + - Method + - Metodă + - Reference + - Referencja + - WindowBase64 +translation_of: Web/API/WindowOrWorkerGlobalScope/atob +original_slug: Web/API/WindowOrWorkerGlobalScope/atob +--- +

{{APIRef}}

+

Funkcja WindowBase64.atob() dekoduje ciąg danych, który został zakodowany używając kodowania base-64. Możesz użyć metody window.btoa() aby zakodować i przesłać dane, które w innym wypadku mogą powodować problemy z komunikacją, a następnie odebrać je i użyć metody window.atob() aby zdekodować dane ponownie. Na przykład możesz zakodować, przesłać i zdekodować znaki kontrolne ASCII o wartościach od 0 do 31.

+

Aby używać tej funkcji z ciągami Unicode albo UTF-8, zobacz tę uwagę w Kodowaniu i dekodowaniu Base64 i tę uwagę w window.btoa().

+

Składnia

+
var odkodowaneDane = window.atob(zakodowaneDane);
+

Przykład

+
var zakodowaneDane = window.btoa("Hello, world"); // kodowanie ciągu
+var odkodowaneDane = window.atob(zakodowaneDane); // odkodowywanie ciągu
+

Specyfikacje

+ + + + + + + + + + + + + + + + + + + + + + + + + +
SpecyfikacjaStatusKomentarz
{{SpecName('HTML WHATWG', '#dom-windowbase64-atob', 'WindowBase64.atob()')}}{{Spec2('HTML WHATWG')}}Bez zmian od ostatniej migawki, {{SpecName("HTML5.1")}}.
{{SpecName('HTML5.1', '#dom-windowbase64-atob', 'WindowBase64.atob()')}}{{Spec2('HTML5.1')}}Migawka {{SpecName("HTML WHATWG")}}. Bez zmian.
{{SpecName("HTML5 W3C", "#dom-windowbase64-atob", "WindowBase64.atob()")}}{{Spec2('HTML5 W3C')}}Migawka {{SpecName("HTML WHATWG")}}. Utworzenie WindowBase64 (properties where on the target before it).
+

Zgodność przeglądarek

+
+ {{CompatibilityTable}}
+
+ + + + + + + + + + + + + + + + + + + +
FunkcjaChromeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Podstawowa obsługa{{CompatVersionUnknown}}{{CompatGeckoDesktop(1)}}[1][2]10{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+
+ + + + + + + + + + + + + + + + + + + +
FunkcjaAndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Podstawowa obsługa{{CompatVersionUnknown}}{{CompatGeckoMobile(1)}}{{CompatNo}}{{CompatUnknown}}{{CompatVersionUnknown}}
+
+

[1]  btoa() jest także dostępna dla komponentów XPCOM zaimplementowanych w JavaScript, nawet jeżeli window nie jest globalnym obiektem w komponencie.

+

[2] Wraz z Firefoxem 27, metoda atob() ignoruje wszystkie spacje w argumencie dla zgodności z najnowszą specyfikacją HTML5. ({{ bug(711180) }})

+

Zobacz też

+ diff --git a/files/pl/web/api/btoa/index.html b/files/pl/web/api/btoa/index.html new file mode 100644 index 0000000000..82f706f632 --- /dev/null +++ b/files/pl/web/api/btoa/index.html @@ -0,0 +1,127 @@ +--- +title: WindowBase64.btoa() +slug: Web/API/btoa +tags: + - API + - Base-64 + - Base64 + - Method + - Reference + - Referencja + - WindowBase64 +translation_of: Web/API/WindowOrWorkerGlobalScope/btoa +original_slug: Web/API/WindowOrWorkerGlobalScope/btoa +--- +

{{APIRef}}

+

Tworzy string ASCII zakodowany w base-64 z ciągu ("string") danych binarnych.

+

Metoda ta jednak nie nadaje się do konwertowania surowych ciągów Unicode! Zobacz sekcję Unicode poniżej.

+

Składnia

+
var zakodowaneDane = window.btoa(ciagDoZakodowania);
+

Przykład

+
var zakodowaneDane = window.btoa("Hello, world"); // kodowanie ciągu
+var odkodowaneDane = window.atob(zakodowaneDane); // odkodowywanie ciągu ("Hello, world")
+
+

Uwagi

+

Możesz używać tej metody do kodowania danych, które w innym wypadku mogą powodować problemy z komunikacją. Przekaż je, a następnie użyj metody window.atob() aby odkodować dane ponownie. Na przykład możesz zakodować znaki kontrolne takie jak ASCII o wartości od 0 do 31.

+

btoa() jest także dostępne dla komponentów XPCOM zaimplementowanych w JavaScript, nawet jeżeli window nie jest globalnym obiektem w komponencie.

+

Ciągi Unicode

+

W większości przeglądarek odwołanie się do window.btoa() z ciągiem Unicode spowoduje wystąpienie wyjątku Character Out Of Range.

+

Aby tego uniknąć, rozważ ten model odnotowany przez Johana Sundströma:

+
function utf8_to_b64( str ) {
+    return window.btoa(encodeURIComponent( escape( str )));
+}
+
+function b64_to_utf8( str ) {
+    return unescape(decodeURIComponent(window.atob( str )));
+}
+
+// Usage:
+utf8_to_b64('✓ à la mode'); // JTI1dTI3MTMlMjUyMCUyNUUwJTI1MjBsYSUyNTIwbW9kZQ==
+b64_to_utf8('JTI1dTI3MTMlMjUyMCUyNUUwJTI1MjBsYSUyNTIwbW9kZQ=='); // "✓ à la mode"
+
+utf8_to_b64('I \u2661 Unicode!'); // SSUyNTIwJTI1dTI2NjElMjUyMFVuaWNvZGUlMjUyMQ==
+b64_to_utf8('SSUyNTIwJTI1dTI2NjElMjUyMFVuaWNvZGUlMjUyMQ=='); // "I ♡ Unicode!"
+
+
+

Lepszym, bardziej wiarygodnym i mniej wymagającym rozwiązaniem jest konwersja DOMString do ciągu zakodowanego w UTF-8 używając TypedArray. W tym celu proszę zapoznać się z tym akapitem.

+

Specyfikacje

+ + + + + + + + + + + + + + + + + + + + + + + + + +
SpecyfikacjaStatusKomentarz
{{SpecName('HTML WHATWG', '#dom-windowbase64-btoa', 'WindowBase64.btoa()')}}{{Spec2('HTML WHATWG')}}Brak zmian od ostatniej migawki, {{SpecName("HTML5.1")}}.
{{SpecName('HTML5.1', '#dom-windowbase64-btoa', 'WindowBase64.btoa()')}}{{Spec2('HTML5.1')}}Migawka {{SpecName("HTML WHATWG")}}. Bez zmian.
{{SpecName("HTML5 W3C", "#dom-windowbase64-btoa", "WindowBase64.btoa()")}}{{Spec2('HTML5 W3C')}}Migawka {{SpecName("HTML WHATWG")}}. Utworzenie WindowBase64 (properties where on the target before it).
+

Zgodność przeglądarek

+
+ {{CompatibilityTable}}
+
+ + + + + + + + + + + + + + + + + + + +
FunkcjaChromeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Podstawowa obsługa{{CompatVersionUnknown}}{{CompatGeckoDesktop(1)}}[1]10{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+
+ + + + + + + + + + + + + + + + + + + +
FunkcjaAndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Podstawowa obsługa{{CompatVersionUnknown}}{{CompatGeckoMobile(1)}}{{CompatNo}}{{CompatUnknown}}{{CompatVersionUnknown}}
+
+

[1] btoa() jest także dostępna dla komponentów XPCOM zaimplementowanych w JavaScript, nawet jeżeli window nie jest globalnym obiektem w komponencie.

+

Zobacz też

+ diff --git a/files/pl/web/api/clearinterval/index.html b/files/pl/web/api/clearinterval/index.html new file mode 100644 index 0000000000..b944d2303d --- /dev/null +++ b/files/pl/web/api/clearinterval/index.html @@ -0,0 +1,29 @@ +--- +title: window.clearInterval +slug: Web/API/clearInterval +tags: + - Window +translation_of: Web/API/WindowOrWorkerGlobalScope/clearInterval +original_slug: Web/API/WindowOrWorkerGlobalScope/clearInterval +--- +
+ {{ApiRef}}
+

Podsumowanie

+

Anuluje powtarzającą się akcję, która została utworzona korzystając z setInterval().

+

Składnia

+
window.clearInterval(idInterwalu)
+
+

idInterwalu to identyfikator powtarzającej się akcji, która ma zostać anulowana. Ten identyfikator został zwrócony z {{domxref("window.setInterval","setInterval()")}}.

+

Przykład

+

Zobacz przykład z setInterval().

+

Specification

+

{{DOM0}}

+

Zobacz także

+
    +
  • JavaScript zegary
  • +
  • {{domxref("window.setTimeout")}}
  • +
  • {{domxref("window.setInterval")}}
  • +
  • {{domxref("window.clearTimeout")}}
  • +
  • {{domxref("window.requestAnimationFrame")}}
  • +
  • Daemons zarządzanie
  • +
diff --git a/files/pl/web/api/cleartimeout/index.html b/files/pl/web/api/cleartimeout/index.html new file mode 100644 index 0000000000..4a910ca13e --- /dev/null +++ b/files/pl/web/api/cleartimeout/index.html @@ -0,0 +1,41 @@ +--- +title: window.clearTimeout +slug: Web/API/clearTimeout +translation_of: Web/API/WindowOrWorkerGlobalScope/clearTimeout +original_slug: Web/API/WindowOrWorkerGlobalScope/clearTimeout +--- +

{{ ApiRef() }}

+

Podsumowanie

+

Usuwa opóźnienie ustanione przez window.setTimeout().

+

Składnia

+
window.clearTimeout(id)
+
+

gdzie id jest identyfikatorem opóźnienia do usunięcia, który został zwrócony podczas wywołania window.setTimeout().

+

Przykład

+

Uruchomienie poniższego skryptu w kontekscie strony i pojedyncze kliknięcie spowoduje wyświetlenie wiadomości po jednej sekundzie. Jeżeli użytkownik będzie klikał na stronie przynajmniej raz na sekundę wiadomość nigdy nie zostanie wyświetlona.

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

Uwagi

+

Przekazanie niepoprawnego ID do clearTimeout nie powoduje żadnej akcji (żaden błąd nie jest wyrzucany).

+

Specyfikacja

+

{{ DOM0() }}

+

{{ languages( { "en": "en/DOM/window.clearTimeout", "fr": "fr/DOM/window.clearTimeout", "ja": "ja/DOM/window.clearTimeout", "pl": "pl/DOM/window.clearTimeout" } ) }}

diff --git a/files/pl/web/api/setinterval/index.html b/files/pl/web/api/setinterval/index.html new file mode 100644 index 0000000000..0149cda60d --- /dev/null +++ b/files/pl/web/api/setinterval/index.html @@ -0,0 +1,88 @@ +--- +title: window.setInterval +slug: Web/API/setInterval +tags: + - DOM + - DOM_0 + - Dokumentacja_Gecko_DOM + - Gecko + - Wszystkie_kategorie +translation_of: Web/API/WindowOrWorkerGlobalScope/setInterval +original_slug: Web/API/WindowOrWorkerGlobalScope/setInterval +--- +

{{ ApiRef() }}

+ +

Podsumowanie

+ +

Ustawia opóźnienie do cyklicznego wywoływania określonej funkcji.

+ +

Składnia

+ +
var idInterwalu = window.setInterval(funkcja, opóźnienie[, parametr1, parametr2, ...]);
+var idInterwalu = window.setInterval(kod, opóźnienie);
+ +

 Parametry

+ +
    +
  • idInterwalu to identyfikator ustawianego interwału który można przekazać do funkcji window.clearInterval().
  • +
  • funkcja to funkcja, dla której ustawiane jest opóźnienie
  • +
  • kod to ciąg znaków zawierający kod javascript do cyklicznego wykonania. Jest to składnia alternatywna, której wykorzystanie nie jest zalecane z tych samych powodów, co stosowanie eval().
  • +
  • opóźnienie to liczba milisekund (tysięcznych części sekundy), co którą wywoływana będzie funkcja lub kod
  • +
+ +

Należy zwrócić uwagę, że przekazywanie dodatkowych parametrów w pierwszej składni nie działa w Internet Explorerze.

+ +

Przykład

+ +
idInterwalu = window.setInterval(animuj, 500);
+
+ +

 W poniższym przykładzie, funkcja zmienKolorTekstu() będzie wykonywana co sekundę, dopóki użytkownik nie naciśnie przycisku Stop, co spowoduje wywołanie clearInterval() z parametrem idInterwalu.

+ +
<html>
+<head>
+<title>przykład z wykorzystaniem setInterval/clearInterval</title>
+
+<script type="text/javascript">
+var idInterwalu;
+
+function zmienKolor() {
+  idInterwalu = setInterval(zmienKolorTekstu, 1000);
+}
+
+function zmienKolorTekstu() {
+  var elem = document.getElementById("my_box");
+  if (elem.style.color == 'red') {
+    elem.style.color = 'blue';
+  } else {
+    elem.style.color = 'red';
+  }
+}
+
+function zatrzymajZmianeKoloru() {
+  clearInterval(idInterwalu);
+}
+</script>
+</head>
+
+<body onload="zmienKolor();">
+<div id="my_box">
+<p>Hello World</p>
+</div>
+<button onclick="zatrzymajZmianeKoloru();">Stop</button>
+</body>
+</html>
+ +

Uwagi

+ +

Funkcja setInterval() służy do ustawienia opóźnienia dla cyklicznie wywoływanych funkcji, takich jak funkcje animacji.

+ +

Możliwe jest anulowanie wykonania fukcji poprzez wywołanie window.clearInterval().

+ +

Jeżeli funkcja ma zostać wykonana tylko raz a nie być wykonywana cyklicznie to należy skorzystać z  window.setTimeout().

+ +

Specyfikacja

+ +

{{ DOM0() }}

+ +

{{ languages( { "en": "en/DOM/window.setInterval", "fr": "fr/DOM/window.setInterval", "ja": "ja/DOM/window.setInterval", "pl": "pl/DOM/window.setInterval" } ) }}

diff --git a/files/pl/web/api/settimeout/index.html b/files/pl/web/api/settimeout/index.html new file mode 100644 index 0000000000..d49c70ced3 --- /dev/null +++ b/files/pl/web/api/settimeout/index.html @@ -0,0 +1,47 @@ +--- +title: window.setTimeout +slug: Web/API/setTimeout +tags: + - DOM + - DOM_0 + - Dokumentacja_Gecko_DOM + - Gecko + - Wszystkie_kategorie +translation_of: Web/API/WindowOrWorkerGlobalScope/setTimeout +original_slug: Web/API/WindowOrWorkerGlobalScope/setTimeout +--- +

{{ ApiRef() }}

+

Podsumowanie

+

Uruchamia fragment kodu bądź funkcję po określonym odstępie czasu.

+

Składnia

+
id = window.setTimeout(funkcja, opóźnienie[, param1, param2, ...]);
+id = window.setTimeout(kod, opóźnienie);
+
+

gdzie

+
    +
  • funkcja to funkcja, jaką chcesz uruchomić po opóźnieniu +
      +
    • w alternatywnej składni, kod to ciąg znaków z kodem, który będzie wykonany po upływie podanego czasu
    • +
    +
  • +
  • opóźnienie to liczba milisekund (tysięcznych części sekundy), po których upływie wykonana zostanie funkcja
  • +
  • id to identyfikator, którego można użyć z window.clearTimeout
  • +
+

Przykłady

+
window.setTimeout('window.parent.generateOutput()', 1000);
+
+
function generateOutput(aConcise) {
+  if(aConcise)
+    parent.generateConciseOutput();
+  else
+    parent.generateOutput();
+}
+window.setTimeout(generateOutput, 1000, true);
+
+

Zobacz też przykład użycia clearTimeout().

+

Uwagi

+

Możesz anulować opóźnienie wywołania funkcji za pomocą window.clearTimeout().

+

Jeśli chcesz, by funkcja była uruchamiana cyklicznie (np. co każde N milisekund), rozważ wykorzystanie window.setInterval().

+

Specyfikacja

+

{{ DOM0() }}

+

{{ languages( { "en": "en/DOM/window.setTimeout", "fr": "fr/DOM/window.setTimeout", "ja": "ja/DOM/window.setTimeout", "pl": "pl/DOM/window.setTimeout" } ) }}

diff --git a/files/pl/web/api/windoworworkerglobalscope/atob/index.html b/files/pl/web/api/windoworworkerglobalscope/atob/index.html deleted file mode 100644 index 862f7b56fe..0000000000 --- a/files/pl/web/api/windoworworkerglobalscope/atob/index.html +++ /dev/null @@ -1,105 +0,0 @@ ---- -title: WindowBase64.atob() -slug: Web/API/WindowOrWorkerGlobalScope/atob -tags: - - API - - Base-64 - - Base64 - - Method - - Metodă - - Reference - - Referencja - - WindowBase64 -translation_of: Web/API/WindowOrWorkerGlobalScope/atob -original_slug: Web/API/WindowBase64/atob ---- -

{{APIRef}}

-

Funkcja WindowBase64.atob() dekoduje ciąg danych, który został zakodowany używając kodowania base-64. Możesz użyć metody window.btoa() aby zakodować i przesłać dane, które w innym wypadku mogą powodować problemy z komunikacją, a następnie odebrać je i użyć metody window.atob() aby zdekodować dane ponownie. Na przykład możesz zakodować, przesłać i zdekodować znaki kontrolne ASCII o wartościach od 0 do 31.

-

Aby używać tej funkcji z ciągami Unicode albo UTF-8, zobacz tę uwagę w Kodowaniu i dekodowaniu Base64 i tę uwagę w window.btoa().

-

Składnia

-
var odkodowaneDane = window.atob(zakodowaneDane);
-

Przykład

-
var zakodowaneDane = window.btoa("Hello, world"); // kodowanie ciągu
-var odkodowaneDane = window.atob(zakodowaneDane); // odkodowywanie ciągu
-

Specyfikacje

- - - - - - - - - - - - - - - - - - - - - - - - - -
SpecyfikacjaStatusKomentarz
{{SpecName('HTML WHATWG', '#dom-windowbase64-atob', 'WindowBase64.atob()')}}{{Spec2('HTML WHATWG')}}Bez zmian od ostatniej migawki, {{SpecName("HTML5.1")}}.
{{SpecName('HTML5.1', '#dom-windowbase64-atob', 'WindowBase64.atob()')}}{{Spec2('HTML5.1')}}Migawka {{SpecName("HTML WHATWG")}}. Bez zmian.
{{SpecName("HTML5 W3C", "#dom-windowbase64-atob", "WindowBase64.atob()")}}{{Spec2('HTML5 W3C')}}Migawka {{SpecName("HTML WHATWG")}}. Utworzenie WindowBase64 (properties where on the target before it).
-

Zgodność przeglądarek

-
- {{CompatibilityTable}}
-
- - - - - - - - - - - - - - - - - - - -
FunkcjaChromeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Podstawowa obsługa{{CompatVersionUnknown}}{{CompatGeckoDesktop(1)}}[1][2]10{{CompatVersionUnknown}}{{CompatVersionUnknown}}
-
-
- - - - - - - - - - - - - - - - - - - -
FunkcjaAndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Podstawowa obsługa{{CompatVersionUnknown}}{{CompatGeckoMobile(1)}}{{CompatNo}}{{CompatUnknown}}{{CompatVersionUnknown}}
-
-

[1]  btoa() jest także dostępna dla komponentów XPCOM zaimplementowanych w JavaScript, nawet jeżeli window nie jest globalnym obiektem w komponencie.

-

[2] Wraz z Firefoxem 27, metoda atob() ignoruje wszystkie spacje w argumencie dla zgodności z najnowszą specyfikacją HTML5. ({{ bug(711180) }})

-

Zobacz też

- diff --git a/files/pl/web/api/windoworworkerglobalscope/btoa/index.html b/files/pl/web/api/windoworworkerglobalscope/btoa/index.html deleted file mode 100644 index 7c5b95a7ae..0000000000 --- a/files/pl/web/api/windoworworkerglobalscope/btoa/index.html +++ /dev/null @@ -1,127 +0,0 @@ ---- -title: WindowBase64.btoa() -slug: Web/API/WindowOrWorkerGlobalScope/btoa -tags: - - API - - Base-64 - - Base64 - - Method - - Reference - - Referencja - - WindowBase64 -translation_of: Web/API/WindowOrWorkerGlobalScope/btoa -original_slug: Web/API/WindowBase64/btoa ---- -

{{APIRef}}

-

Tworzy string ASCII zakodowany w base-64 z ciągu ("string") danych binarnych.

-

Metoda ta jednak nie nadaje się do konwertowania surowych ciągów Unicode! Zobacz sekcję Unicode poniżej.

-

Składnia

-
var zakodowaneDane = window.btoa(ciagDoZakodowania);
-

Przykład

-
var zakodowaneDane = window.btoa("Hello, world"); // kodowanie ciągu
-var odkodowaneDane = window.atob(zakodowaneDane); // odkodowywanie ciągu ("Hello, world")
-
-

Uwagi

-

Możesz używać tej metody do kodowania danych, które w innym wypadku mogą powodować problemy z komunikacją. Przekaż je, a następnie użyj metody window.atob() aby odkodować dane ponownie. Na przykład możesz zakodować znaki kontrolne takie jak ASCII o wartości od 0 do 31.

-

btoa() jest także dostępne dla komponentów XPCOM zaimplementowanych w JavaScript, nawet jeżeli window nie jest globalnym obiektem w komponencie.

-

Ciągi Unicode

-

W większości przeglądarek odwołanie się do window.btoa() z ciągiem Unicode spowoduje wystąpienie wyjątku Character Out Of Range.

-

Aby tego uniknąć, rozważ ten model odnotowany przez Johana Sundströma:

-
function utf8_to_b64( str ) {
-    return window.btoa(encodeURIComponent( escape( str )));
-}
-
-function b64_to_utf8( str ) {
-    return unescape(decodeURIComponent(window.atob( str )));
-}
-
-// Usage:
-utf8_to_b64('✓ à la mode'); // JTI1dTI3MTMlMjUyMCUyNUUwJTI1MjBsYSUyNTIwbW9kZQ==
-b64_to_utf8('JTI1dTI3MTMlMjUyMCUyNUUwJTI1MjBsYSUyNTIwbW9kZQ=='); // "✓ à la mode"
-
-utf8_to_b64('I \u2661 Unicode!'); // SSUyNTIwJTI1dTI2NjElMjUyMFVuaWNvZGUlMjUyMQ==
-b64_to_utf8('SSUyNTIwJTI1dTI2NjElMjUyMFVuaWNvZGUlMjUyMQ=='); // "I ♡ Unicode!"
-
-
-

Lepszym, bardziej wiarygodnym i mniej wymagającym rozwiązaniem jest konwersja DOMString do ciągu zakodowanego w UTF-8 używając TypedArray. W tym celu proszę zapoznać się z tym akapitem.

-

Specyfikacje

- - - - - - - - - - - - - - - - - - - - - - - - - -
SpecyfikacjaStatusKomentarz
{{SpecName('HTML WHATWG', '#dom-windowbase64-btoa', 'WindowBase64.btoa()')}}{{Spec2('HTML WHATWG')}}Brak zmian od ostatniej migawki, {{SpecName("HTML5.1")}}.
{{SpecName('HTML5.1', '#dom-windowbase64-btoa', 'WindowBase64.btoa()')}}{{Spec2('HTML5.1')}}Migawka {{SpecName("HTML WHATWG")}}. Bez zmian.
{{SpecName("HTML5 W3C", "#dom-windowbase64-btoa", "WindowBase64.btoa()")}}{{Spec2('HTML5 W3C')}}Migawka {{SpecName("HTML WHATWG")}}. Utworzenie WindowBase64 (properties where on the target before it).
-

Zgodność przeglądarek

-
- {{CompatibilityTable}}
-
- - - - - - - - - - - - - - - - - - - -
FunkcjaChromeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Podstawowa obsługa{{CompatVersionUnknown}}{{CompatGeckoDesktop(1)}}[1]10{{CompatVersionUnknown}}{{CompatVersionUnknown}}
-
-
- - - - - - - - - - - - - - - - - - - -
FunkcjaAndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Podstawowa obsługa{{CompatVersionUnknown}}{{CompatGeckoMobile(1)}}{{CompatNo}}{{CompatUnknown}}{{CompatVersionUnknown}}
-
-

[1] btoa() jest także dostępna dla komponentów XPCOM zaimplementowanych w JavaScript, nawet jeżeli window nie jest globalnym obiektem w komponencie.

-

Zobacz też

- diff --git a/files/pl/web/api/windoworworkerglobalscope/clearinterval/index.html b/files/pl/web/api/windoworworkerglobalscope/clearinterval/index.html deleted file mode 100644 index e4ecb8701d..0000000000 --- a/files/pl/web/api/windoworworkerglobalscope/clearinterval/index.html +++ /dev/null @@ -1,29 +0,0 @@ ---- -title: window.clearInterval -slug: Web/API/WindowOrWorkerGlobalScope/clearInterval -tags: - - Window -translation_of: Web/API/WindowOrWorkerGlobalScope/clearInterval -original_slug: Web/API/Window/clearInterval ---- -
- {{ApiRef}}
-

Podsumowanie

-

Anuluje powtarzającą się akcję, która została utworzona korzystając z setInterval().

-

Składnia

-
window.clearInterval(idInterwalu)
-
-

idInterwalu to identyfikator powtarzającej się akcji, która ma zostać anulowana. Ten identyfikator został zwrócony z {{domxref("window.setInterval","setInterval()")}}.

-

Przykład

-

Zobacz przykład z setInterval().

-

Specification

-

{{DOM0}}

-

Zobacz także

-
    -
  • JavaScript zegary
  • -
  • {{domxref("window.setTimeout")}}
  • -
  • {{domxref("window.setInterval")}}
  • -
  • {{domxref("window.clearTimeout")}}
  • -
  • {{domxref("window.requestAnimationFrame")}}
  • -
  • Daemons zarządzanie
  • -
diff --git a/files/pl/web/api/windoworworkerglobalscope/cleartimeout/index.html b/files/pl/web/api/windoworworkerglobalscope/cleartimeout/index.html deleted file mode 100644 index b57e9d04b4..0000000000 --- a/files/pl/web/api/windoworworkerglobalscope/cleartimeout/index.html +++ /dev/null @@ -1,41 +0,0 @@ ---- -title: window.clearTimeout -slug: Web/API/WindowOrWorkerGlobalScope/clearTimeout -translation_of: Web/API/WindowOrWorkerGlobalScope/clearTimeout -original_slug: Web/API/Window/clearTimeout ---- -

{{ ApiRef() }}

-

Podsumowanie

-

Usuwa opóźnienie ustanione przez window.setTimeout().

-

Składnia

-
window.clearTimeout(id)
-
-

gdzie id jest identyfikatorem opóźnienia do usunięcia, który został zwrócony podczas wywołania window.setTimeout().

-

Przykład

-

Uruchomienie poniższego skryptu w kontekscie strony i pojedyncze kliknięcie spowoduje wyświetlenie wiadomości po jednej sekundzie. Jeżeli użytkownik będzie klikał na stronie przynajmniej raz na sekundę wiadomość nigdy nie zostanie wyświetlona.

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

Uwagi

-

Przekazanie niepoprawnego ID do clearTimeout nie powoduje żadnej akcji (żaden błąd nie jest wyrzucany).

-

Specyfikacja

-

{{ DOM0() }}

-

{{ languages( { "en": "en/DOM/window.clearTimeout", "fr": "fr/DOM/window.clearTimeout", "ja": "ja/DOM/window.clearTimeout", "pl": "pl/DOM/window.clearTimeout" } ) }}

diff --git a/files/pl/web/api/windoworworkerglobalscope/setinterval/index.html b/files/pl/web/api/windoworworkerglobalscope/setinterval/index.html deleted file mode 100644 index 277b9c44d7..0000000000 --- a/files/pl/web/api/windoworworkerglobalscope/setinterval/index.html +++ /dev/null @@ -1,88 +0,0 @@ ---- -title: window.setInterval -slug: Web/API/WindowOrWorkerGlobalScope/setInterval -tags: - - DOM - - DOM_0 - - Dokumentacja_Gecko_DOM - - Gecko - - Wszystkie_kategorie -translation_of: Web/API/WindowOrWorkerGlobalScope/setInterval -original_slug: Web/API/Window/setInterval ---- -

{{ ApiRef() }}

- -

Podsumowanie

- -

Ustawia opóźnienie do cyklicznego wywoływania określonej funkcji.

- -

Składnia

- -
var idInterwalu = window.setInterval(funkcja, opóźnienie[, parametr1, parametr2, ...]);
-var idInterwalu = window.setInterval(kod, opóźnienie);
- -

 Parametry

- -
    -
  • idInterwalu to identyfikator ustawianego interwału który można przekazać do funkcji window.clearInterval().
  • -
  • funkcja to funkcja, dla której ustawiane jest opóźnienie
  • -
  • kod to ciąg znaków zawierający kod javascript do cyklicznego wykonania. Jest to składnia alternatywna, której wykorzystanie nie jest zalecane z tych samych powodów, co stosowanie eval().
  • -
  • opóźnienie to liczba milisekund (tysięcznych części sekundy), co którą wywoływana będzie funkcja lub kod
  • -
- -

Należy zwrócić uwagę, że przekazywanie dodatkowych parametrów w pierwszej składni nie działa w Internet Explorerze.

- -

Przykład

- -
idInterwalu = window.setInterval(animuj, 500);
-
- -

 W poniższym przykładzie, funkcja zmienKolorTekstu() będzie wykonywana co sekundę, dopóki użytkownik nie naciśnie przycisku Stop, co spowoduje wywołanie clearInterval() z parametrem idInterwalu.

- -
<html>
-<head>
-<title>przykład z wykorzystaniem setInterval/clearInterval</title>
-
-<script type="text/javascript">
-var idInterwalu;
-
-function zmienKolor() {
-  idInterwalu = setInterval(zmienKolorTekstu, 1000);
-}
-
-function zmienKolorTekstu() {
-  var elem = document.getElementById("my_box");
-  if (elem.style.color == 'red') {
-    elem.style.color = 'blue';
-  } else {
-    elem.style.color = 'red';
-  }
-}
-
-function zatrzymajZmianeKoloru() {
-  clearInterval(idInterwalu);
-}
-</script>
-</head>
-
-<body onload="zmienKolor();">
-<div id="my_box">
-<p>Hello World</p>
-</div>
-<button onclick="zatrzymajZmianeKoloru();">Stop</button>
-</body>
-</html>
- -

Uwagi

- -

Funkcja setInterval() służy do ustawienia opóźnienia dla cyklicznie wywoływanych funkcji, takich jak funkcje animacji.

- -

Możliwe jest anulowanie wykonania fukcji poprzez wywołanie window.clearInterval().

- -

Jeżeli funkcja ma zostać wykonana tylko raz a nie być wykonywana cyklicznie to należy skorzystać z  window.setTimeout().

- -

Specyfikacja

- -

{{ DOM0() }}

- -

{{ languages( { "en": "en/DOM/window.setInterval", "fr": "fr/DOM/window.setInterval", "ja": "ja/DOM/window.setInterval", "pl": "pl/DOM/window.setInterval" } ) }}

diff --git a/files/pl/web/api/windoworworkerglobalscope/settimeout/index.html b/files/pl/web/api/windoworworkerglobalscope/settimeout/index.html deleted file mode 100644 index bfe274a8f7..0000000000 --- a/files/pl/web/api/windoworworkerglobalscope/settimeout/index.html +++ /dev/null @@ -1,47 +0,0 @@ ---- -title: window.setTimeout -slug: Web/API/WindowOrWorkerGlobalScope/setTimeout -tags: - - DOM - - DOM_0 - - Dokumentacja_Gecko_DOM - - Gecko - - Wszystkie_kategorie -translation_of: Web/API/WindowOrWorkerGlobalScope/setTimeout -original_slug: Web/API/Window/setTimeout ---- -

{{ ApiRef() }}

-

Podsumowanie

-

Uruchamia fragment kodu bądź funkcję po określonym odstępie czasu.

-

Składnia

-
id = window.setTimeout(funkcja, opóźnienie[, param1, param2, ...]);
-id = window.setTimeout(kod, opóźnienie);
-
-

gdzie

-
    -
  • funkcja to funkcja, jaką chcesz uruchomić po opóźnieniu -
      -
    • w alternatywnej składni, kod to ciąg znaków z kodem, który będzie wykonany po upływie podanego czasu
    • -
    -
  • -
  • opóźnienie to liczba milisekund (tysięcznych części sekundy), po których upływie wykonana zostanie funkcja
  • -
  • id to identyfikator, którego można użyć z window.clearTimeout
  • -
-

Przykłady

-
window.setTimeout('window.parent.generateOutput()', 1000);
-
-
function generateOutput(aConcise) {
-  if(aConcise)
-    parent.generateConciseOutput();
-  else
-    parent.generateOutput();
-}
-window.setTimeout(generateOutput, 1000, true);
-
-

Zobacz też przykład użycia clearTimeout().

-

Uwagi

-

Możesz anulować opóźnienie wywołania funkcji za pomocą window.clearTimeout().

-

Jeśli chcesz, by funkcja była uruchamiana cyklicznie (np. co każde N milisekund), rozważ wykorzystanie window.setInterval().

-

Specyfikacja

-

{{ DOM0() }}

-

{{ languages( { "en": "en/DOM/window.setTimeout", "fr": "fr/DOM/window.setTimeout", "ja": "ja/DOM/window.setTimeout", "pl": "pl/DOM/window.setTimeout" } ) }}

diff --git a/files/pt-br/_redirects.txt b/files/pt-br/_redirects.txt index 6f1dea3e46..d8fbb3ee68 100644 --- a/files/pt-br/_redirects.txt +++ b/files/pt-br/_redirects.txt @@ -539,9 +539,13 @@ /pt-BR/docs/Web/API/Window.navigator /pt-BR/docs/Web/API/Window/navigator /pt-BR/docs/Web/API/Window.openDialog /pt-BR/docs/Web/API/Window/openDialog /pt-BR/docs/Web/API/Window/Window.localStorage /pt-BR/docs/Web/API/Window/localStorage -/pt-BR/docs/Web/API/WindowBase64/atob /pt-BR/docs/Web/API/WindowOrWorkerGlobalScope/atob -/pt-BR/docs/Web/API/WindowTimers.clearTimeout /pt-BR/docs/Web/API/WindowOrWorkerGlobalScope/clearTimeout -/pt-BR/docs/Web/API/WindowTimers/clearTimeout /pt-BR/docs/Web/API/WindowOrWorkerGlobalScope/clearTimeout +/pt-BR/docs/Web/API/WindowBase64/atob /pt-BR/docs/Web/API/atob +/pt-BR/docs/Web/API/WindowOrWorkerGlobalScope/atob /pt-BR/docs/Web/API/atob +/pt-BR/docs/Web/API/WindowOrWorkerGlobalScope/clearTimeout /pt-BR/docs/Web/API/clearTimeout +/pt-BR/docs/Web/API/WindowOrWorkerGlobalScope/fetch /pt-BR/docs/Web/API/fetch +/pt-BR/docs/Web/API/WindowOrWorkerGlobalScope/setInterval /pt-BR/docs/Web/API/setInterval +/pt-BR/docs/Web/API/WindowTimers.clearTimeout /pt-BR/docs/Web/API/clearTimeout +/pt-BR/docs/Web/API/WindowTimers/clearTimeout /pt-BR/docs/Web/API/clearTimeout /pt-BR/docs/Web/API/XMLHttpRequest/Requisicoes_sincronas_e_assincronas /pt-BR/docs/Web/API/XMLHttpRequest/Synchronous_and_Asynchronous_Requests /pt-BR/docs/Web/API/XMLHttpRequest/Usando_XMLHttpRequest /pt-BR/docs/Web/API/XMLHttpRequest/Using_XMLHttpRequest /pt-BR/docs/Web/API/document.getElementById /pt-BR/docs/Web/API/Document/getElementById diff --git a/files/pt-br/_wikihistory.json b/files/pt-br/_wikihistory.json index 017e0afb74..2c13008b4e 100644 --- a/files/pt-br/_wikihistory.json +++ b/files/pt-br/_wikihistory.json @@ -6880,33 +6880,6 @@ "Bzbarsky" ] }, - "Web/API/WindowOrWorkerGlobalScope/atob": { - "modified": "2020-10-15T21:46:04.009Z", - "contributors": [ - "mateusvelleda", - "joaoricardo_rm" - ] - }, - "Web/API/WindowOrWorkerGlobalScope/clearTimeout": { - "modified": "2020-10-15T21:31:54.685Z", - "contributors": [ - "GarkGarcia", - "teoli", - "Willkuns" - ] - }, - "Web/API/WindowOrWorkerGlobalScope/fetch": { - "modified": "2019-03-23T22:06:21.567Z", - "contributors": [ - "dowgssss" - ] - }, - "Web/API/WindowOrWorkerGlobalScope/setInterval": { - "modified": "2020-10-15T22:16:56.864Z", - "contributors": [ - "luan0ap" - ] - }, "Web/API/Worker": { "modified": "2020-10-28T22:21:09.210Z", "contributors": [ @@ -7014,6 +6987,33 @@ "trestini" ] }, + "Web/API/atob": { + "modified": "2020-10-15T21:46:04.009Z", + "contributors": [ + "mateusvelleda", + "joaoricardo_rm" + ] + }, + "Web/API/clearTimeout": { + "modified": "2020-10-15T21:31:54.685Z", + "contributors": [ + "GarkGarcia", + "teoli", + "Willkuns" + ] + }, + "Web/API/fetch": { + "modified": "2019-03-23T22:06:21.567Z", + "contributors": [ + "dowgssss" + ] + }, + "Web/API/setInterval": { + "modified": "2020-10-15T22:16:56.864Z", + "contributors": [ + "luan0ap" + ] + }, "Web/Accessibility": { "modified": "2019-09-09T14:18:55.700Z", "contributors": [ diff --git a/files/pt-br/web/api/atob/index.html b/files/pt-br/web/api/atob/index.html new file mode 100644 index 0000000000..694f3ed6a7 --- /dev/null +++ b/files/pt-br/web/api/atob/index.html @@ -0,0 +1,73 @@ +--- +title: WindowBase64.atob() +slug: Web/API/atob +tags: + - API + - Referencia + - WindowBase64 + - metodo +translation_of: Web/API/WindowOrWorkerGlobalScope/atob +original_slug: Web/API/WindowOrWorkerGlobalScope/atob +--- +
{{APIRef("HTML DOM")}}
+ +

A função WindowBase64.atob() decodifica uma string de dados que foi codificada através da codificação base-64. Você pode usar o método {{domxref("WindowBase64.btoa","window.btoa()")}} para codificar e transmitir dados que, se não codificados, podem causar problemas de comunicação. Após transmití-los pode-se usar o método window.atob() para decodificar os dados novamente. Por exemplo, você pode codificar, transmitir,  e decodificar caracteres de controle como valores ASCII de 0 a 31.

+ +

Para utilizar com strings Unicode ou UTF-8, veja esta nota em Base64 encoding and decoding e essa nota em window.btoa().

+ +

Sintaxe

+ +
var dadoDecodificado = window.atob(dadoCodificado);
+ +

Exemplo

+ +
var dadoCodificado = window.btoa("Olá, mundo"); // codifica a string
+var dadoDecodificado = window.atob(dadoCodificado); // decodifica a string
+ +

Especificações

+ + + + + + + + + + + + + + + + + + + + + + + + + + +
EspecificaçãoStatusComentário
{{SpecName('HTML WHATWG', '#dom-windowbase64-atob', 'WindowBase64.atob()')}}{{Spec2('HTML WHATWG')}}Nenhuma mudança desde a última versão, {{SpecName("HTML5.1")}}.
{{SpecName('HTML5.1', '#dom-windowbase64-atob', 'WindowBase64.atob()')}}{{Spec2('HTML5.1')}}Versão de {{SpecName("HTML WHATWG")}}. Nenhuma mudança.
{{SpecName("HTML5 W3C", "#dom-windowbase64-atob", "WindowBase64.atob()")}}{{Spec2('HTML5 W3C')}}Versão de {{SpecName("HTML WHATWG")}}. Criação do WindowBase64 (antes as propriedades ficavam no target).
+ +

Compatibilidade com navegadores

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

[1] atob() também está disponível para os componentes do XPCOM implementado em JavaScript, porém o objeto window não é global nos componentes.

+ +

[2] A partir do Firefox 27, atob() ignora todos os caracteres de espaço no argumento para seguir as últimas especificações do HTML5. ({{bug(711180)}})

+ +

Veja também

+ + diff --git a/files/pt-br/web/api/cleartimeout/index.html b/files/pt-br/web/api/cleartimeout/index.html new file mode 100644 index 0000000000..e2dd7650b4 --- /dev/null +++ b/files/pt-br/web/api/cleartimeout/index.html @@ -0,0 +1,101 @@ +--- +title: WindowTimers.clearTimeout() +slug: Web/API/clearTimeout +tags: + - API + - Method + - Window +translation_of: Web/API/WindowOrWorkerGlobalScope/clearTimeout +original_slug: Web/API/WindowOrWorkerGlobalScope/clearTimeout +--- +
+
+
{{APIRef("HTML DOM")}}
+
+
+ +

Sumário

+ +

O método clearTimeout() do escopo {{domxref("WindowOrWorkerGlobalScope")}} cancela um timeout previamente estabelecido pela função {{domxref("WindowOrWorkerGlobalScope.setTimeout", "setTimeout()")}}.

+ +

Síntaxe

+ +
escopo.clearTimeout(timeoutID)
+
+ +

Parâmetros

+ +
+
timeoutID
+
O ID do timeout que você deseja cancelar. Esse ID é o retorno da função setTimeout().
+
+ +

É interessante ressaltar que os conjuntso de IDs usados pelos métodos {{domxref("WindowOrWorkerGlobalScope.setTimeout", "setTimeout()")}} e {{domxref("WindowOrWorkerGlobalScope.setInterval", "setInterval()")}} são compartilhados, o que significa que clearTimeout() e {{domxref("WindowOrWorkerGlobalScope.clearInterval", "clearInterval()")}} podem ser tecnicamente utilizados de forma intercambiável. No entanto, para obter-se maior clareza, isso deve ser evitado.

+ +

Exemplo

+ +

Execute o script abaixo em uma página web e clique na página uma vez. Você verá uma mensagem aparecer um segundo depois. Se você continuar clicando na página várias vezes nesse intervalo de tempo, a mensagem aparecerá uma única vez.

+ +
var alarme = {
+  relembrar: function(aMessage) {
+    alert(aMessage);
+    delete this.timeoutID;
+  },
+
+  setup: function() {
+    if (typeof this.timeoutID === 'number') {
+        this.cancelar();
+    }
+
+    this.timeoutID = window.setTimeout(function(msg) {
+        this.relembrar(msg);
+    }.bind(this), 1000, 'Wake up!');
+  },
+
+  cancelar: function() {
+    window.clearTimeout(this.timeoutID);
+  }
+};
+window.onclick = function() { alarme.setup() };
+ +

Notas

+ +

Passar um ID inválido para clearTimeout não causa nenhum efeito (não lança nenhuma exceção).

+ +

Especificações

+ + + + + + + + + + + + + + + + + + + +
EspecificaçãoStatusComentário
{{SpecName('HTML WHATWG', 'webappapis.html#dom-cleartimeout', 'WindowOrWorkerGlobalScope.clearTimeout()')}}{{Spec2("HTML WHATWG")}}Método movido para WindowOrWorkerGlobalScope .
{{SpecName('HTML WHATWG', 'webappapis.html#dom-cleartimeout', 'clearTimeout()')}}{{Spec2('HTML WHATWG')}} 
+ +

Compatibilidade

+ + + +

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

+ +

Veja também

+ +
    +
  • {{domxref("WindowOrWorkerGlobalScope.setTimeout()")}}
  • +
  • {{domxref("WindowOrWorkerGlobalScope.setInterval()")}}
  • +
  • {{domxref("WindowOrWorkerGlobalScope.clearInterval()")}}
  • +
  • {{domxref("Window.requestAnimationFrame()")}}
  • +
  • Daemons management
  • +
diff --git a/files/pt-br/web/api/fetch/index.html b/files/pt-br/web/api/fetch/index.html new file mode 100644 index 0000000000..f864600c86 --- /dev/null +++ b/files/pt-br/web/api/fetch/index.html @@ -0,0 +1,306 @@ +--- +title: WindowOrWorkerGlobalScope.fetch() +slug: Web/API/fetch +translation_of: Web/API/WindowOrWorkerGlobalScope/fetch +original_slug: Web/API/WindowOrWorkerGlobalScope/fetch +--- +
{{APIRef("Fetch API")}}
+ +

O método fetch() do mixin {{domxref("WindowOrWorkerGlobalScope")}} inicia um processo de busca de um recurso da rede. Este, retorna uma promessa que resolve o objeto {{domxref("Response")}} que representa a resposta a sua requisição. 

+ +

WorkerOrGlobalScope é implementado por {{domxref("Window")}} e {{domxref("WorkerGlobalScope")}}, o que significa que o método fetch() está disponível em praticamente qualquer contexto em que você possa querer obter recursos.

+ +

Uma promessa {{domxref("WindowOrWorkerGlobalScope.fetch","fetch()")}} rejeita com um {{jsxref("TypeError")}} quando um erro de rede é encontrado, embora isso geralmente signifique um problema de permissões ou similar. Uma verificação precisa de um fetch() bem-sucedido incluiria a verificação de uma promessa resolvida, e depois verificando se a propriedade {{domxref("Response.ok")}} possui valor true. Um status HTTP 404 não constitui um erro de rede.

+ +

O método fetch() é controlado pela diretiva connect-src da Content Security Policy em vez da diretiva dos recursos que está recuperando.

+ +
+

Nota: Os parâmetros do método fetch() são idênticos aos do construtor {{domxref("Request.Request","Request()")}}.

+
+ +

Sintaxe

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

Parâmetros

+ +
+
input
+
Isto define o recurso que você deseja buscar. Isto pode ser: +
    +
  • Um {{domxref("USVString")}} contendo uma URL direta para o recurso que você quer obter. Alguns navegadores aceitam blob: e data: como esquemas.
  • +
  • Um objeto {{domxref("Request")}}.
  • +
+
+
init {{optional_inline}}
+
Um objeto opcional que contém configurações personalizadas que você pode aplicar à requisição. As opções possíveis são: +
    +
  • method: Método HTTP, por exemplo, GET, POST.
  • +
  • headers: Qualquer cabeçalho que você queira adicionar à sua requisição, contido dentro de um objeto {{domxref("Headers")}} ou um objeto literal com valores {{domxref("ByteString")}}.
  • +
  • body: Qualquer corpo que você queira adicionar à sua requisição: podendo ser um {{domxref("Blob")}}, {{domxref("BufferSource")}}, {{domxref("FormData")}}, {{domxref("URLSearchParams")}}, ou um objeto {{domxref("USVString")}}. Note que uma requisição usando os métodos GET ou HEAD não pode ter um corpo.
  • +
  • mode: O modo que deseja usar para a requisição, por exemplo, cors, no-cors, ou same-origin.
  • +
  • credentials: A credencial que deseja usar para a requisição: omit, same-origin, ou include. Para enviar automaticamente cookies para o domínio atual, esta opção deve ser fornecida. Começando com o Chrome 50, essa propriedade também usa uma instância {{domxref("FederatedCredential")}} ou uma instância {{domxref("PasswordCredential")}}.
  • +
  • cache: O modo de cache que deseja usar na requisição: default, no-store, reload, no-cache, force-cache, ou only-if-cached.
  • +
  • redirect: O modo de redirecionamento pode usar: follow (segue automaticamente o redirecionamento), error (aborta com um erro se ocorrer um redirecionamento), ou manual (manipula redirecionamentos manualmente). No Chrome o padrão foi follow antes do Chrome 47 e manual a partir do Chrome 47.
  • +
  • referrer: Um {{domxref("USVString")}} especificando no-referrerclient, ou uma URL. O padrão é client.
  • +
  • referrerPolicy: Especifica o valor do cabeçalho HTTP referer. Pode ser um destes: no-referrer, no-referrer-when-downgrade, origin, origin-when-cross-origin, unsafe-url.
  • +
  • integrity: Contém o valor de integridade de subrecurso da requisição (por exemplo, sha256-BpfBw7ivV8q2jLiT13fxDYAe2tJllusRSZ273h2nFSE=).
  • +
  • signal: Uma instância do objeto {{domxref("FetchSignal")}}; permite que você se comunique com um pedido de busca e controle-o através de um {{domxref("FetchController")}}. {{non-standard_inline}}
  • +
  • observe: Um objeto {{domxref("ObserverCallback")}} — o objetivo exclusivo deste objeto é fornecer uma função de retorno de chamada que é executada quando a solicitação fetch é executada. Isto retorna um objeto {{domxref("FetchObserver")}} que pode ser usado para recuperar informações sobre o status de uma solicitação fetch. {{non-standard_inline}}
  • +
+
+
+ +

Valor de Retorno

+ +

Uma {{domxref("Promise")}} que resolve um objeto {{domxref("Response")}}.

+ +

Exceptions

+ + + + + + + + + + + + + + +
TipoDescrição
TypeErrorDesdo o Firefox 43, fetch()
+ lançará um TypeError se a URL tiver credenciais, como http://user:password@example.com.
+ +

Example

+ +

In our Fetch Request example (see Fetch Request live) we create a new {{domxref("Request")}} object using the relevant constructor, then fetch it using a fetch() call. Since we are fetching an image, we run {{domxref("Body.blob()")}} on the response to give it the proper MIME type so it will be handled properly, then create an Object URL of it and display it in an {{htmlelement("img")}} element.

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

In our Fetch with init then Request example (see Fetch Request init live) we do the same thing except that we pass in an init object when we invoke fetch():

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

Note that you could also pass the init object in with the Request constructor to get the same effect, e.g.:

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

You can also use an object literal as headers in init.

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

Specifications

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

Compatibilidade com navegadores

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureChromeEdgeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Basic support{{CompatChrome(42)}}14{{CompatGeckoDesktop(34)}}[1]
+ {{CompatGeckoDesktop(39)}}
+ {{CompatGeckoDesktop(52)}}[2]
{{CompatNo}}29
+ 28[1]
{{CompatNo}}
Streaming response body{{CompatChrome(43)}}14{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
Support for blob: and data:{{CompatChrome(48)}}{{CompatNo}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
referrerPolicy{{CompatChrome(52)}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}39{{CompatUnknown}}
signal and observer{{ CompatNo }}{{ CompatNo }}{{ CompatNo }}[3]{{ CompatNo }}{{ CompatNo }}{{ CompatNo }}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidAndroid WebviewEdgeFirefox Mobile (Gecko)IE PhoneOpera MobileSafari MobileChrome for Android
Basic support{{CompatNo}}{{CompatChrome(42)}}14{{CompatGeckoMobile(52)}}[2]{{CompatNo}}{{CompatNo}}{{CompatNo}}{{CompatChrome(42)}}
Streaming response body{{CompatNo}}{{CompatChrome(43)}}14{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatChrome(43)}}
Support for blob: and data:{{CompatNo}}{{CompatChrome(43)}}{{CompatNo}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatChrome(43)}}
referrerPolicy{{CompatNo}}{{CompatChrome(52)}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}39{{CompatUnknown}}{{CompatChrome(52)}}
signal and observer{{ CompatNo }}{{ CompatNo }}{{ CompatNo }}{{ CompatNo }}[3]{{ CompatNo }}{{ CompatNo }}{{ CompatNo }}{{ CompatNo }}
+
+ +

[1] API is implemented behind a preference.

+ +

[2] fetch() now defined on {{domxref("WindowOrWorkerGlobalScope")}} mixin.

+ +

[3] Hidden behind a preference in 55+ Nightly. In about:config, you need to create two new boolean prefs — dom.fetchObserver.enabled and dom.fetchController.enabled — and set the values of both to true.

+ +

See also

+ + diff --git a/files/pt-br/web/api/setinterval/index.html b/files/pt-br/web/api/setinterval/index.html new file mode 100644 index 0000000000..213cc50492 --- /dev/null +++ b/files/pt-br/web/api/setinterval/index.html @@ -0,0 +1,630 @@ +--- +title: WindowOrWorkerGlobalScope.setInterval() +slug: Web/API/setInterval +translation_of: Web/API/WindowOrWorkerGlobalScope/setInterval +original_slug: Web/API/WindowOrWorkerGlobalScope/setInterval +--- +
{{APIRef("HTML DOM")}}
+ +
 
+ +

O método setInterval() oferecido das interfaces {{domxref("Window")}} e {{domxref("Worker")}}, repetem chamadas de funções or executam trechos de código, com um tempo de espera fixo entre cada chamada. Isso retorna um ID único para o intervalo, podendo remove-lo mais tarde apenas o chamando {{domxref("WindowOrWorkerGlobalScope.clearInterval", "clearInterval()")}}. Este metodo é definido pelo mixin {{domxref("WindowOrWorkerGlobalScope")}}.

+ +

Sintaxe.

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

Parâmetros

+ +
+
func
+
Uma {{jsxref("function")}} para ser executada a cada delay em milisegundos.  Não é passado nenhum parâmetro para a função, e não retorna nenhum valor esperado.
+
code
+
Uma sintaxe opcional permite você incuir uma string ao invés de uma função, no qual é compilado e executada a cada delay em milisegundos. Esta sintaxe não é recomendada pelos mesmos motivos que envolvem riscos de segurança de {{jsxref("eval", "eval()")}}.
+
delay
+
O tempo, em milisegundos (milésimos de segundo), o temporizador deve atrasar entre cada execução de uma especifica função ou código. Se esse parâmetro for menos que 10, um valor de 10 é usado. Note que o atraso pode vir a ser mais longo; veja {{SectionOnPage("/en-US/docs/Web/API/WindowOrWorkerGlobalScope/setTimeout", "Reasons for delays longer than specified")}} para exemplos.
+
param1, ..., paramN {{optional_inline}}
+
Parâmetros adicionais que são passados através da função especificada pela func quando o temporizador expirar.
+
+ +
+

Note: Passing additional parameters to setInterval() in the first syntax does not work in Internet Explorer 9 and earlier. If you want to enable this functionality on that browser, you must use a polyfill (see the Callback arguments section).

+
+ +

Return value

+ +

intervalID retornado é um número, non-zero valor que identifica o temporizador criado pela chamada do setInterval(); este valor pode ser passado para {{domxref("WindowOrWorkerGlobalScope.clearInterval()")}} afim de cancelar o timeout.

+ +

Isso pode ser útil, estar ciente que o setInterval() e {{domxref("WindowOrWorkerGlobalScope.setTimeout", "setTimeout()")}} compartilham o mesmo grupo de IDs, e que o clearInterval() e {{domxref("WindowOrWorkerGlobalScope.clearTimeout", "clearTimeout()")}} podem tecnicamente serem usados em conjunto. Para deixar claro, contudo, você deve sempre tentar evitar combina-los, afim de evitar confusão na manutenção do seu código.

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

Exemplos

+ +

Exemplo 1: Sintaxe básica

+ +

O seguinte exemplo mostra a sintaxe básica do setInterval()

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

Exemplo 2: Alternando duas cores

+ +

O seguinte exemplo chama a função flashtext() uma vez por segundo até o botão de parar ser pressionado.

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

Exemplo 3: Simulação de máquina de escrever

+ +

O seguinte exemplo simula uma máquina de escrever primeiro limpando e digitando lentamente o conteúdo para  NodeList que corresponde a um grupo especificado de seletores.

+ +
<!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().

+ +

Argumentos callback

+ +

Como já foi discutido, Internet Explorer 9 e versões anteriores não suportam passar argumentos para a função callback em ambos setTimeout() ou setInterval(). O seguinte código IE-specific demonstra um método para superar esta limitação. Para usar, apenas adicione o seguinte código no topo do seu script.

+ +
/*\
+|*|
+|*|  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;
+}
+
+ +

Outra possibilidade é uso uma função anônima para chama o callback, apesar de que esta solução seja um pouco mais pesada. Exemplo:

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

Outra possibilidade é usar o function's bind. Exemplo:

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

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

+ +

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

+ +

O problema do "this"

+ +

Quando você passa um método para setInterval() ou qualquer outra função, ela é chamada com o valor do this errado. Este problema é explicado em detalhes em JavaScript reference.

+ +

Explicação

+ +

O código executado pelo setInterval() roda em um contexto de execução separado da função que foi chamada. Como uma consequência, o this da função chamada, é setado como o objeto window (ou global), esse não é o mesmo valor do this para a função chamada em setTimeout. veja o seguinte exemplo (que usa setTimeout() ao invés de setInterval() - o problema segue para ambos os temporizadores)

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

 

+ +

Como você pode ver, não há maneiras de passar o objeto this para a função callback.

+ +

 

+ +

Uma possível solução

+ +

Um possível caminho para resolver o problema do this, é sobreescrever as duas funções globais nativas setTimeout() ou setInterval() com duas non-native que permitem sua invocação através do método Function.prototype.call. O seguinte exemplo mostra a possível substituição.

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

Teste da nova implementação:

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

Outra, mais complexa, solução para o problema do this é the following framework.

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

MiniDaemon - A framework for managing timers

+ +

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

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

minidaemon.js

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

Syntax

+ +

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

+ +

Description

+ +

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

+ +

Parameters

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

MiniDaemon instances properties

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

MiniDaemon instances methods

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

MiniDaemon global object methods

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

Example usage

+ +

Your HTML page:

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

View this example in action

+ +

Notes

+ +

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

+ +

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

+ +

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

+ +

Ensure that execution duration is shorter than interval frequency

+ +

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

+ +

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

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

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

+ +

Throttling of intervals

+ +

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

+ +

Specifications

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

Compatibilidade com navegadores

+ +
+ + +

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

+
+ +

See also

+ +
    +
  • JavaScript timers
  • +
  • {{domxref("WindowOrWorkerGlobalScope.setTimeout")}}
  • +
  • {{domxref("WindowOrWorkerGlobalScope.clearTimeout")}}
  • +
  • {{domxref("WindowOrWorkerGlobalScope.clearInterval")}}
  • +
  • {{domxref("window.requestAnimationFrame")}}
  • +
  • Daemons management
  • +
diff --git a/files/pt-br/web/api/windoworworkerglobalscope/atob/index.html b/files/pt-br/web/api/windoworworkerglobalscope/atob/index.html deleted file mode 100644 index 4448a8b31f..0000000000 --- a/files/pt-br/web/api/windoworworkerglobalscope/atob/index.html +++ /dev/null @@ -1,73 +0,0 @@ ---- -title: WindowBase64.atob() -slug: Web/API/WindowOrWorkerGlobalScope/atob -tags: - - API - - Referencia - - WindowBase64 - - metodo -translation_of: Web/API/WindowOrWorkerGlobalScope/atob -original_slug: Web/API/WindowBase64/atob ---- -
{{APIRef("HTML DOM")}}
- -

A função WindowBase64.atob() decodifica uma string de dados que foi codificada através da codificação base-64. Você pode usar o método {{domxref("WindowBase64.btoa","window.btoa()")}} para codificar e transmitir dados que, se não codificados, podem causar problemas de comunicação. Após transmití-los pode-se usar o método window.atob() para decodificar os dados novamente. Por exemplo, você pode codificar, transmitir,  e decodificar caracteres de controle como valores ASCII de 0 a 31.

- -

Para utilizar com strings Unicode ou UTF-8, veja esta nota em Base64 encoding and decoding e essa nota em window.btoa().

- -

Sintaxe

- -
var dadoDecodificado = window.atob(dadoCodificado);
- -

Exemplo

- -
var dadoCodificado = window.btoa("Olá, mundo"); // codifica a string
-var dadoDecodificado = window.atob(dadoCodificado); // decodifica a string
- -

Especificações

- - - - - - - - - - - - - - - - - - - - - - - - - - -
EspecificaçãoStatusComentário
{{SpecName('HTML WHATWG', '#dom-windowbase64-atob', 'WindowBase64.atob()')}}{{Spec2('HTML WHATWG')}}Nenhuma mudança desde a última versão, {{SpecName("HTML5.1")}}.
{{SpecName('HTML5.1', '#dom-windowbase64-atob', 'WindowBase64.atob()')}}{{Spec2('HTML5.1')}}Versão de {{SpecName("HTML WHATWG")}}. Nenhuma mudança.
{{SpecName("HTML5 W3C", "#dom-windowbase64-atob", "WindowBase64.atob()")}}{{Spec2('HTML5 W3C')}}Versão de {{SpecName("HTML WHATWG")}}. Criação do WindowBase64 (antes as propriedades ficavam no target).
- -

Compatibilidade com navegadores

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

[1] atob() também está disponível para os componentes do XPCOM implementado em JavaScript, porém o objeto window não é global nos componentes.

- -

[2] A partir do Firefox 27, atob() ignora todos os caracteres de espaço no argumento para seguir as últimas especificações do HTML5. ({{bug(711180)}})

- -

Veja também

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

Sumário

- -

O método clearTimeout() do escopo {{domxref("WindowOrWorkerGlobalScope")}} cancela um timeout previamente estabelecido pela função {{domxref("WindowOrWorkerGlobalScope.setTimeout", "setTimeout()")}}.

- -

Síntaxe

- -
escopo.clearTimeout(timeoutID)
-
- -

Parâmetros

- -
-
timeoutID
-
O ID do timeout que você deseja cancelar. Esse ID é o retorno da função setTimeout().
-
- -

É interessante ressaltar que os conjuntso de IDs usados pelos métodos {{domxref("WindowOrWorkerGlobalScope.setTimeout", "setTimeout()")}} e {{domxref("WindowOrWorkerGlobalScope.setInterval", "setInterval()")}} são compartilhados, o que significa que clearTimeout() e {{domxref("WindowOrWorkerGlobalScope.clearInterval", "clearInterval()")}} podem ser tecnicamente utilizados de forma intercambiável. No entanto, para obter-se maior clareza, isso deve ser evitado.

- -

Exemplo

- -

Execute o script abaixo em uma página web e clique na página uma vez. Você verá uma mensagem aparecer um segundo depois. Se você continuar clicando na página várias vezes nesse intervalo de tempo, a mensagem aparecerá uma única vez.

- -
var alarme = {
-  relembrar: function(aMessage) {
-    alert(aMessage);
-    delete this.timeoutID;
-  },
-
-  setup: function() {
-    if (typeof this.timeoutID === 'number') {
-        this.cancelar();
-    }
-
-    this.timeoutID = window.setTimeout(function(msg) {
-        this.relembrar(msg);
-    }.bind(this), 1000, 'Wake up!');
-  },
-
-  cancelar: function() {
-    window.clearTimeout(this.timeoutID);
-  }
-};
-window.onclick = function() { alarme.setup() };
- -

Notas

- -

Passar um ID inválido para clearTimeout não causa nenhum efeito (não lança nenhuma exceção).

- -

Especificações

- - - - - - - - - - - - - - - - - - - -
EspecificaçãoStatusComentário
{{SpecName('HTML WHATWG', 'webappapis.html#dom-cleartimeout', 'WindowOrWorkerGlobalScope.clearTimeout()')}}{{Spec2("HTML WHATWG")}}Método movido para WindowOrWorkerGlobalScope .
{{SpecName('HTML WHATWG', 'webappapis.html#dom-cleartimeout', 'clearTimeout()')}}{{Spec2('HTML WHATWG')}} 
- -

Compatibilidade

- - - -

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

- -

Veja também

- -
    -
  • {{domxref("WindowOrWorkerGlobalScope.setTimeout()")}}
  • -
  • {{domxref("WindowOrWorkerGlobalScope.setInterval()")}}
  • -
  • {{domxref("WindowOrWorkerGlobalScope.clearInterval()")}}
  • -
  • {{domxref("Window.requestAnimationFrame()")}}
  • -
  • Daemons management
  • -
diff --git a/files/pt-br/web/api/windoworworkerglobalscope/fetch/index.html b/files/pt-br/web/api/windoworworkerglobalscope/fetch/index.html deleted file mode 100644 index 4567730f6c..0000000000 --- a/files/pt-br/web/api/windoworworkerglobalscope/fetch/index.html +++ /dev/null @@ -1,305 +0,0 @@ ---- -title: WindowOrWorkerGlobalScope.fetch() -slug: Web/API/WindowOrWorkerGlobalScope/fetch -translation_of: Web/API/WindowOrWorkerGlobalScope/fetch ---- -
{{APIRef("Fetch API")}}
- -

O método fetch() do mixin {{domxref("WindowOrWorkerGlobalScope")}} inicia um processo de busca de um recurso da rede. Este, retorna uma promessa que resolve o objeto {{domxref("Response")}} que representa a resposta a sua requisição. 

- -

WorkerOrGlobalScope é implementado por {{domxref("Window")}} e {{domxref("WorkerGlobalScope")}}, o que significa que o método fetch() está disponível em praticamente qualquer contexto em que você possa querer obter recursos.

- -

Uma promessa {{domxref("WindowOrWorkerGlobalScope.fetch","fetch()")}} rejeita com um {{jsxref("TypeError")}} quando um erro de rede é encontrado, embora isso geralmente signifique um problema de permissões ou similar. Uma verificação precisa de um fetch() bem-sucedido incluiria a verificação de uma promessa resolvida, e depois verificando se a propriedade {{domxref("Response.ok")}} possui valor true. Um status HTTP 404 não constitui um erro de rede.

- -

O método fetch() é controlado pela diretiva connect-src da Content Security Policy em vez da diretiva dos recursos que está recuperando.

- -
-

Nota: Os parâmetros do método fetch() são idênticos aos do construtor {{domxref("Request.Request","Request()")}}.

-
- -

Sintaxe

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

Parâmetros

- -
-
input
-
Isto define o recurso que você deseja buscar. Isto pode ser: -
    -
  • Um {{domxref("USVString")}} contendo uma URL direta para o recurso que você quer obter. Alguns navegadores aceitam blob: e data: como esquemas.
  • -
  • Um objeto {{domxref("Request")}}.
  • -
-
-
init {{optional_inline}}
-
Um objeto opcional que contém configurações personalizadas que você pode aplicar à requisição. As opções possíveis são: -
    -
  • method: Método HTTP, por exemplo, GET, POST.
  • -
  • headers: Qualquer cabeçalho que você queira adicionar à sua requisição, contido dentro de um objeto {{domxref("Headers")}} ou um objeto literal com valores {{domxref("ByteString")}}.
  • -
  • body: Qualquer corpo que você queira adicionar à sua requisição: podendo ser um {{domxref("Blob")}}, {{domxref("BufferSource")}}, {{domxref("FormData")}}, {{domxref("URLSearchParams")}}, ou um objeto {{domxref("USVString")}}. Note que uma requisição usando os métodos GET ou HEAD não pode ter um corpo.
  • -
  • mode: O modo que deseja usar para a requisição, por exemplo, cors, no-cors, ou same-origin.
  • -
  • credentials: A credencial que deseja usar para a requisição: omit, same-origin, ou include. Para enviar automaticamente cookies para o domínio atual, esta opção deve ser fornecida. Começando com o Chrome 50, essa propriedade também usa uma instância {{domxref("FederatedCredential")}} ou uma instância {{domxref("PasswordCredential")}}.
  • -
  • cache: O modo de cache que deseja usar na requisição: default, no-store, reload, no-cache, force-cache, ou only-if-cached.
  • -
  • redirect: O modo de redirecionamento pode usar: follow (segue automaticamente o redirecionamento), error (aborta com um erro se ocorrer um redirecionamento), ou manual (manipula redirecionamentos manualmente). No Chrome o padrão foi follow antes do Chrome 47 e manual a partir do Chrome 47.
  • -
  • referrer: Um {{domxref("USVString")}} especificando no-referrerclient, ou uma URL. O padrão é client.
  • -
  • referrerPolicy: Especifica o valor do cabeçalho HTTP referer. Pode ser um destes: no-referrer, no-referrer-when-downgrade, origin, origin-when-cross-origin, unsafe-url.
  • -
  • integrity: Contém o valor de integridade de subrecurso da requisição (por exemplo, sha256-BpfBw7ivV8q2jLiT13fxDYAe2tJllusRSZ273h2nFSE=).
  • -
  • signal: Uma instância do objeto {{domxref("FetchSignal")}}; permite que você se comunique com um pedido de busca e controle-o através de um {{domxref("FetchController")}}. {{non-standard_inline}}
  • -
  • observe: Um objeto {{domxref("ObserverCallback")}} — o objetivo exclusivo deste objeto é fornecer uma função de retorno de chamada que é executada quando a solicitação fetch é executada. Isto retorna um objeto {{domxref("FetchObserver")}} que pode ser usado para recuperar informações sobre o status de uma solicitação fetch. {{non-standard_inline}}
  • -
-
-
- -

Valor de Retorno

- -

Uma {{domxref("Promise")}} que resolve um objeto {{domxref("Response")}}.

- -

Exceptions

- - - - - - - - - - - - - - -
TipoDescrição
TypeErrorDesdo o Firefox 43, fetch()
- lançará um TypeError se a URL tiver credenciais, como http://user:password@example.com.
- -

Example

- -

In our Fetch Request example (see Fetch Request live) we create a new {{domxref("Request")}} object using the relevant constructor, then fetch it using a fetch() call. Since we are fetching an image, we run {{domxref("Body.blob()")}} on the response to give it the proper MIME type so it will be handled properly, then create an Object URL of it and display it in an {{htmlelement("img")}} element.

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

In our Fetch with init then Request example (see Fetch Request init live) we do the same thing except that we pass in an init object when we invoke fetch():

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

Note that you could also pass the init object in with the Request constructor to get the same effect, e.g.:

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

You can also use an object literal as headers in init.

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

Specifications

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

Compatibilidade com navegadores

- -

{{CompatibilityTable}}

- -
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
FeatureChromeEdgeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Basic support{{CompatChrome(42)}}14{{CompatGeckoDesktop(34)}}[1]
- {{CompatGeckoDesktop(39)}}
- {{CompatGeckoDesktop(52)}}[2]
{{CompatNo}}29
- 28[1]
{{CompatNo}}
Streaming response body{{CompatChrome(43)}}14{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
Support for blob: and data:{{CompatChrome(48)}}{{CompatNo}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
referrerPolicy{{CompatChrome(52)}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}39{{CompatUnknown}}
signal and observer{{ CompatNo }}{{ CompatNo }}{{ CompatNo }}[3]{{ CompatNo }}{{ CompatNo }}{{ CompatNo }}
-
- -
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
FeatureAndroidAndroid WebviewEdgeFirefox Mobile (Gecko)IE PhoneOpera MobileSafari MobileChrome for Android
Basic support{{CompatNo}}{{CompatChrome(42)}}14{{CompatGeckoMobile(52)}}[2]{{CompatNo}}{{CompatNo}}{{CompatNo}}{{CompatChrome(42)}}
Streaming response body{{CompatNo}}{{CompatChrome(43)}}14{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatChrome(43)}}
Support for blob: and data:{{CompatNo}}{{CompatChrome(43)}}{{CompatNo}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatChrome(43)}}
referrerPolicy{{CompatNo}}{{CompatChrome(52)}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}39{{CompatUnknown}}{{CompatChrome(52)}}
signal and observer{{ CompatNo }}{{ CompatNo }}{{ CompatNo }}{{ CompatNo }}[3]{{ CompatNo }}{{ CompatNo }}{{ CompatNo }}{{ CompatNo }}
-
- -

[1] API is implemented behind a preference.

- -

[2] fetch() now defined on {{domxref("WindowOrWorkerGlobalScope")}} mixin.

- -

[3] Hidden behind a preference in 55+ Nightly. In about:config, you need to create two new boolean prefs — dom.fetchObserver.enabled and dom.fetchController.enabled — and set the values of both to true.

- -

See also

- - diff --git a/files/pt-br/web/api/windoworworkerglobalscope/setinterval/index.html b/files/pt-br/web/api/windoworworkerglobalscope/setinterval/index.html deleted file mode 100644 index 65dfe562f3..0000000000 --- a/files/pt-br/web/api/windoworworkerglobalscope/setinterval/index.html +++ /dev/null @@ -1,629 +0,0 @@ ---- -title: WindowOrWorkerGlobalScope.setInterval() -slug: Web/API/WindowOrWorkerGlobalScope/setInterval -translation_of: Web/API/WindowOrWorkerGlobalScope/setInterval ---- -
{{APIRef("HTML DOM")}}
- -
 
- -

O método setInterval() oferecido das interfaces {{domxref("Window")}} e {{domxref("Worker")}}, repetem chamadas de funções or executam trechos de código, com um tempo de espera fixo entre cada chamada. Isso retorna um ID único para o intervalo, podendo remove-lo mais tarde apenas o chamando {{domxref("WindowOrWorkerGlobalScope.clearInterval", "clearInterval()")}}. Este metodo é definido pelo mixin {{domxref("WindowOrWorkerGlobalScope")}}.

- -

Sintaxe.

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

Parâmetros

- -
-
func
-
Uma {{jsxref("function")}} para ser executada a cada delay em milisegundos.  Não é passado nenhum parâmetro para a função, e não retorna nenhum valor esperado.
-
code
-
Uma sintaxe opcional permite você incuir uma string ao invés de uma função, no qual é compilado e executada a cada delay em milisegundos. Esta sintaxe não é recomendada pelos mesmos motivos que envolvem riscos de segurança de {{jsxref("eval", "eval()")}}.
-
delay
-
O tempo, em milisegundos (milésimos de segundo), o temporizador deve atrasar entre cada execução de uma especifica função ou código. Se esse parâmetro for menos que 10, um valor de 10 é usado. Note que o atraso pode vir a ser mais longo; veja {{SectionOnPage("/en-US/docs/Web/API/WindowOrWorkerGlobalScope/setTimeout", "Reasons for delays longer than specified")}} para exemplos.
-
param1, ..., paramN {{optional_inline}}
-
Parâmetros adicionais que são passados através da função especificada pela func quando o temporizador expirar.
-
- -
-

Note: Passing additional parameters to setInterval() in the first syntax does not work in Internet Explorer 9 and earlier. If you want to enable this functionality on that browser, you must use a polyfill (see the Callback arguments section).

-
- -

Return value

- -

intervalID retornado é um número, non-zero valor que identifica o temporizador criado pela chamada do setInterval(); este valor pode ser passado para {{domxref("WindowOrWorkerGlobalScope.clearInterval()")}} afim de cancelar o timeout.

- -

Isso pode ser útil, estar ciente que o setInterval() e {{domxref("WindowOrWorkerGlobalScope.setTimeout", "setTimeout()")}} compartilham o mesmo grupo de IDs, e que o clearInterval() e {{domxref("WindowOrWorkerGlobalScope.clearTimeout", "clearTimeout()")}} podem tecnicamente serem usados em conjunto. Para deixar claro, contudo, você deve sempre tentar evitar combina-los, afim de evitar confusão na manutenção do seu código.

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

Exemplos

- -

Exemplo 1: Sintaxe básica

- -

O seguinte exemplo mostra a sintaxe básica do setInterval()

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

Exemplo 2: Alternando duas cores

- -

O seguinte exemplo chama a função flashtext() uma vez por segundo até o botão de parar ser pressionado.

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

Exemplo 3: Simulação de máquina de escrever

- -

O seguinte exemplo simula uma máquina de escrever primeiro limpando e digitando lentamente o conteúdo para  NodeList que corresponde a um grupo especificado de seletores.

- -
<!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().

- -

Argumentos callback

- -

Como já foi discutido, Internet Explorer 9 e versões anteriores não suportam passar argumentos para a função callback em ambos setTimeout() ou setInterval(). O seguinte código IE-specific demonstra um método para superar esta limitação. Para usar, apenas adicione o seguinte código no topo do seu script.

- -
/*\
-|*|
-|*|  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;
-}
-
- -

Outra possibilidade é uso uma função anônima para chama o callback, apesar de que esta solução seja um pouco mais pesada. Exemplo:

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

Outra possibilidade é usar o function's bind. Exemplo:

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

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

- -

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

- -

O problema do "this"

- -

Quando você passa um método para setInterval() ou qualquer outra função, ela é chamada com o valor do this errado. Este problema é explicado em detalhes em JavaScript reference.

- -

Explicação

- -

O código executado pelo setInterval() roda em um contexto de execução separado da função que foi chamada. Como uma consequência, o this da função chamada, é setado como o objeto window (ou global), esse não é o mesmo valor do this para a função chamada em setTimeout. veja o seguinte exemplo (que usa setTimeout() ao invés de setInterval() - o problema segue para ambos os temporizadores)

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

 

- -

Como você pode ver, não há maneiras de passar o objeto this para a função callback.

- -

 

- -

Uma possível solução

- -

Um possível caminho para resolver o problema do this, é sobreescrever as duas funções globais nativas setTimeout() ou setInterval() com duas non-native que permitem sua invocação através do método Function.prototype.call. O seguinte exemplo mostra a possível substituição.

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

Teste da nova implementação:

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

Outra, mais complexa, solução para o problema do this é the following framework.

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

MiniDaemon - A framework for managing timers

- -

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

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

minidaemon.js

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

Syntax

- -

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

- -

Description

- -

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

- -

Parameters

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

MiniDaemon instances properties

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

MiniDaemon instances methods

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

MiniDaemon global object methods

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

Example usage

- -

Your HTML page:

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

View this example in action

- -

Notes

- -

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

- -

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

- -

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

- -

Ensure that execution duration is shorter than interval frequency

- -

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

- -

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

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

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

- -

Throttling of intervals

- -

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

- -

Specifications

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

Compatibilidade com navegadores

- -
- - -

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

-
- -

See also

- -
    -
  • JavaScript timers
  • -
  • {{domxref("WindowOrWorkerGlobalScope.setTimeout")}}
  • -
  • {{domxref("WindowOrWorkerGlobalScope.clearTimeout")}}
  • -
  • {{domxref("WindowOrWorkerGlobalScope.clearInterval")}}
  • -
  • {{domxref("window.requestAnimationFrame")}}
  • -
  • Daemons management
  • -
diff --git a/files/ru/_redirects.txt b/files/ru/_redirects.txt index 3a867ba603..8dbb1dd636 100644 --- a/files/ru/_redirects.txt +++ b/files/ru/_redirects.txt @@ -365,9 +365,16 @@ /ru/docs/Web/API/WebRTC_API/протоколы /ru/docs/Web/API/WebRTC_API/Protocols /ru/docs/Web/API/WebRTC_API/связь /ru/docs/Web/API/WebRTC_API/Connectivity /ru/docs/Web/API/WindowBase64/Base64_encoding_and_decoding /ru/docs/Glossary/Base64 -/ru/docs/Web/API/WindowBase64/btoa /ru/docs/Web/API/WindowOrWorkerGlobalScope/btoa -/ru/docs/Web/API/WindowTimers.setTimeout /ru/docs/Web/API/WindowOrWorkerGlobalScope/setTimeout -/ru/docs/Web/API/WindowTimers/setTimeout /ru/docs/Web/API/WindowOrWorkerGlobalScope/setTimeout +/ru/docs/Web/API/WindowBase64/btoa /ru/docs/Web/API/btoa +/ru/docs/Web/API/WindowOrWorkerGlobalScope/atob /ru/docs/Web/API/atob +/ru/docs/Web/API/WindowOrWorkerGlobalScope/btoa /ru/docs/Web/API/btoa +/ru/docs/Web/API/WindowOrWorkerGlobalScope/caches /ru/docs/Web/API/caches +/ru/docs/Web/API/WindowOrWorkerGlobalScope/clearTimeout /ru/docs/Web/API/clearTimeout +/ru/docs/Web/API/WindowOrWorkerGlobalScope/fetch /ru/docs/Web/API/fetch +/ru/docs/Web/API/WindowOrWorkerGlobalScope/setInterval /ru/docs/Web/API/setInterval +/ru/docs/Web/API/WindowOrWorkerGlobalScope/setTimeout /ru/docs/Web/API/setTimeout +/ru/docs/Web/API/WindowTimers.setTimeout /ru/docs/Web/API/setTimeout +/ru/docs/Web/API/WindowTimers/setTimeout /ru/docs/Web/API/setTimeout /ru/docs/Web/API/console.timeEnd /ru/docs/Web/API/Console/timeEnd /ru/docs/Web/API/document.activeElement /ru/docs/Web/API/Document/activeElement /ru/docs/Web/API/document.createComment /ru/docs/Web/API/Document/createComment diff --git a/files/ru/_wikihistory.json b/files/ru/_wikihistory.json index 1e12d65056..633ebd6995 100644 --- a/files/ru/_wikihistory.json +++ b/files/ru/_wikihistory.json @@ -11658,62 +11658,6 @@ "kenrick95" ] }, - "Web/API/WindowOrWorkerGlobalScope/atob": { - "modified": "2019-03-23T22:02:40.728Z", - "contributors": [ - "HawkeyePierce89", - "hunty" - ] - }, - "Web/API/WindowOrWorkerGlobalScope/btoa": { - "modified": "2019-09-17T16:11:11.862Z", - "contributors": [ - "SerzN1", - "uleming" - ] - }, - "Web/API/WindowOrWorkerGlobalScope/caches": { - "modified": "2020-10-29T09:02:45.566Z", - "contributors": [ - "ScratchFilin", - "evilwithin93rus" - ] - }, - "Web/API/WindowOrWorkerGlobalScope/clearTimeout": { - "modified": "2020-10-15T22:33:31.469Z", - "contributors": [ - "andzion105" - ] - }, - "Web/API/WindowOrWorkerGlobalScope/fetch": { - "modified": "2020-10-15T22:06:28.491Z", - "contributors": [ - "BadLame", - "dasha_hshr" - ] - }, - "Web/API/WindowOrWorkerGlobalScope/setInterval": { - "modified": "2020-11-18T12:13:20.493Z", - "contributors": [ - "kosarev_va", - "WhiteApfel", - "lilka9", - "AliaksandrZahorski" - ] - }, - "Web/API/WindowOrWorkerGlobalScope/setTimeout": { - "modified": "2020-11-18T12:03:29.649Z", - "contributors": [ - "kosarev_va", - "YozhEzhi", - "AliaksandrZahorski", - "akaguny", - "marat-curious", - "neustroev.artyom", - "fscholz", - "ichent" - ] - }, "Web/API/Worker": { "modified": "2019-03-23T22:47:25.398Z", "contributors": [ @@ -11959,6 +11903,40 @@ "t1gor" ] }, + "Web/API/atob": { + "modified": "2019-03-23T22:02:40.728Z", + "contributors": [ + "HawkeyePierce89", + "hunty" + ] + }, + "Web/API/btoa": { + "modified": "2019-09-17T16:11:11.862Z", + "contributors": [ + "SerzN1", + "uleming" + ] + }, + "Web/API/caches": { + "modified": "2020-10-29T09:02:45.566Z", + "contributors": [ + "ScratchFilin", + "evilwithin93rus" + ] + }, + "Web/API/clearTimeout": { + "modified": "2020-10-15T22:33:31.469Z", + "contributors": [ + "andzion105" + ] + }, + "Web/API/fetch": { + "modified": "2020-10-15T22:06:28.491Z", + "contributors": [ + "BadLame", + "dasha_hshr" + ] + }, "Web/API/notification": { "modified": "2019-03-23T22:43:07.772Z", "contributors": [ @@ -11969,6 +11947,28 @@ "fsanano" ] }, + "Web/API/setInterval": { + "modified": "2020-11-18T12:13:20.493Z", + "contributors": [ + "kosarev_va", + "WhiteApfel", + "lilka9", + "AliaksandrZahorski" + ] + }, + "Web/API/setTimeout": { + "modified": "2020-11-18T12:03:29.649Z", + "contributors": [ + "kosarev_va", + "YozhEzhi", + "AliaksandrZahorski", + "akaguny", + "marat-curious", + "neustroev.artyom", + "fscholz", + "ichent" + ] + }, "Web/API/window/requestAnimationFrame": { "modified": "2020-10-15T21:21:09.538Z", "contributors": [ diff --git a/files/ru/web/api/atob/index.html b/files/ru/web/api/atob/index.html new file mode 100644 index 0000000000..931c4deb95 --- /dev/null +++ b/files/ru/web/api/atob/index.html @@ -0,0 +1,71 @@ +--- +title: WindowOrWorkerGlobalScope.atob() +slug: Web/API/atob +translation_of: Web/API/WindowOrWorkerGlobalScope/atob +original_slug: Web/API/WindowOrWorkerGlobalScope/atob +--- +
{{APIRef("HTML DOM")}}
+ +

Функция WindowOrWorkerGlobalScope.atob() декодирует строку данных, которая была закодирована с использованием  base-64. Вы можете использовать метод {{domxref("WindowOrWorkerGlobalScope.btoa","btoa()")}}, чтобы декодировать и передать данные, которые в исходном виде могут вызвать проблемы  передачи, затем отправить их, и использовать метод atob() чтобы декодировать даны снова. Например, вы можете закодировать, передать, и декодировать управляющие символы, такие как ASCII значения от 0 до 31.

+ +

В случаях использования с Unicode или UTF-8 строками, смотрите this note at Base64 encoding and decoding и this note at btoa().

+ +

Синтаксис

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

Throws

+ +

Выбрасывает {{jsxref("DOMException")}}, если длина переданной строки не кратна 4.

+ +

Пример

+ +
var encodedData = window.btoa('Hello, world'); // кодирует строку
+var decodedData = window.atob(encodedData); // декодирует строку
+ +

Спецификации

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
СпецификацияСтатусКомментарий
{{SpecName('HTML WHATWG', 'webappapis.html#dom-btoa', 'WindowOrWorkerGlobalScope.atob()')}}{{Spec2('HTML WHATWG')}}Method moved to the WindowOrWorkerGlobalScope mixin in the latest spec.
{{SpecName('HTML WHATWG', '#dom-windowbase64-atob', 'WindowBase64.atob()')}}{{Spec2('HTML WHATWG')}}No change since the latest snapshot, {{SpecName("HTML5.1")}}.
{{SpecName('HTML5.1', '#dom-windowbase64-atob', 'WindowBase64.atob()')}}{{Spec2('HTML5.1')}}Snapshot of {{SpecName("HTML WHATWG")}}. No change.
{{SpecName("HTML5 W3C", "#dom-windowbase64-atob", "WindowBase64.atob()")}}{{Spec2('HTML5 W3C')}}Snapshot of {{SpecName("HTML WHATWG")}}. Creation of WindowBase64 (properties were on the target before it).
+ +

Совместимость с браузерами

+ +

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

+ +

Смотрите также

+ + diff --git a/files/ru/web/api/btoa/index.html b/files/ru/web/api/btoa/index.html new file mode 100644 index 0000000000..12080d8fa6 --- /dev/null +++ b/files/ru/web/api/btoa/index.html @@ -0,0 +1,94 @@ +--- +title: WindowBase64.btoa() +slug: Web/API/btoa +translation_of: Web/API/WindowOrWorkerGlobalScope/btoa +original_slug: Web/API/WindowOrWorkerGlobalScope/btoa +--- +
{{APIRef("HTML DOM")}}
+ +

Создаёт ASCII строку закодированную в base-64 из "строки" бинарных данных.

+ +

Будьте внимательней этот способ не подходит для Unicode строк! Описание работы с Unicode в секции ниже.

+ +

Синтаксис

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

Пример

+ +
var encodedData = window.btoa("Hello, world"); // encode a string
+var decodedData = window.atob(encodedData); // decode the string
+
+ +

Замечания

+ +

Вы можете воспользоваться этим способом, чтобы избежать проблем при передаче данных через сетевое соединение. Для этого нужно перекодировать данные в base64 и отправить их, и на другой стороне с помощью метода {{domxref("WindowBase64.atob","window.atob()")}} декодировать полученные данные в исходный вид. Например, вы можете перекодировать управляющие символы ASCII с 0 до 31.

+ +

btoa() также доступна для XPCOM компонентов реализованных в JavaScript, даже если window не является глобальным объектом в компонентах.

+ +

Строки Юникод

+ +

В большинстве браузеров, вызов window.btoa() на Unicode строке выбросит исключение Character Out Of Range (Символ вне допустимого диапазона).

+ +

Чтобы избежать этого, воспользуйтесь паттерном, предложенным Johan Sundström:

+ +
function utf8_to_b64(str) {
+    return window.btoa(unescape(encodeURIComponent(str)));
+}
+
+function b64_to_utf8(str) {
+    return decodeURIComponent(escape(window.atob(str)));
+}
+
+// Usage:
+utf8_to_b64('✓ à la mode'); // JTI1dTI3MTMlMjUyMCUyNUUwJTI1MjBsYSUyNTIwbW9kZQ==
+b64_to_utf8('JTI1dTI3MTMlMjUyMCUyNUUwJTI1MjBsYSUyNTIwbW9kZQ=='); // "✓ à la mode"
+
+utf8_to_b64('I \u2661 Unicode!'); // SSUyNTIwJTI1dTI2NjElMjUyMFVuaWNvZGUlMjUyMQ==
+b64_to_utf8('SSUyNTIwJTI1dTI2NjElMjUyMFVuaWNvZGUlMjUyMQ=='); // "I ♡ Unicode!"
+
+
+ +

Более правильный и производительный способ - это конвертировать DOMString в UTF-8 строку передав typed arrays. Как это сделать узнать можно здесь в этом параграфе.

+ +

Спецификации

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

Совместимость браузеров

+ +

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

+ +

Смотрите также

+ + diff --git a/files/ru/web/api/caches/index.html b/files/ru/web/api/caches/index.html new file mode 100644 index 0000000000..78e2f33014 --- /dev/null +++ b/files/ru/web/api/caches/index.html @@ -0,0 +1,80 @@ +--- +title: WindowOrWorkerGlobalScope.caches +slug: Web/API/caches +translation_of: Web/API/WindowOrWorkerGlobalScope/caches +original_slug: Web/API/WindowOrWorkerGlobalScope/caches +--- +
{{APIRef()}}{{SeeCompatTable}}
+ +

caches {{domxref("WindowOrWorkerGlobalScope")}}  свойство только для чтения интерфейса возвращающее  объект ассоциированный с текущим контекстом {{domxref("CacheStorage")}}.

+ +

Этот объект реализует такую  функциональность как строгое соответствие для офлайн-использования  и генерирование пользовательских ответов на запросы.

+ +

Синтаксис

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

Значение

+ +

Возвращает значение {{domxref("CacheStorage")}} .

+ +

Пример

+ +

Данный пример показывает как надо использовать кеш в контексте service worker для хранения в автономном режиме

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

Спецификации

+ + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('Service Workers', '#self-caches', 'caches')}}{{Spec2('Service Workers')}}Объявлена частичная поддержка в новейшей спецификации WindowOrWorkerGlobalScope.
{{SpecName('Service Workers')}}{{Spec2('Service Workers')}}Начальное определение.
+ +

Совместимость с браузерами

+ + + +

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

+ +

Также смотрите

+ + diff --git a/files/ru/web/api/cleartimeout/index.html b/files/ru/web/api/cleartimeout/index.html new file mode 100644 index 0000000000..e19fc0fe1b --- /dev/null +++ b/files/ru/web/api/cleartimeout/index.html @@ -0,0 +1,95 @@ +--- +title: WindowOrWorkerGlobalScope.clearTimeout() +slug: Web/API/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
+
+
Идентификатор таймаута, который вы хотите отменить. Этот идентификатор был возвращён соответствующим вызовом setTimeout().
+
+ +

It's worth noting that the pool of IDs used by {{domxref("WindowOrWorkerGlobalScope.setTimeout", "setTimeout()")}} and {{domxref("WindowOrWorkerGlobalScope.setInterval", "setInterval()")}} are shared, which means you can technically use clearTimeout() and {{domxref("WindowOrWorkerGlobalScope.clearInterval", "clearInterval()")}} interchangeably. However, for clarity, you should avoid doing so.

+ +

Пример использования:

+ +

Запустите приведённый ниже скрипт в контакте веб-страницы и кликните один раз. Вы увидите всплывающее сообщение через 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(); };
+
+ +

Примечания

+ +

Передача недействительного ID clearTimeout() ни к чему не приведёт. Исключение не создается.

+ +

Спецификация

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

Совместимость с браузером

+ + + +

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

+ +

Смотрите также

+ +
    +
  • {{domxref("WindowOrWorkerGlobalScope.setTimeout()")}}
  • +
  • {{domxref("WindowOrWorkerGlobalScope.setInterval()")}}
  • +
  • {{domxref("WindowOrWorkerGlobalScope.clearInterval()")}}
  • +
  • {{domxref("Window.requestAnimationFrame()")}}
  • +
  • Daemons management
  • +
diff --git a/files/ru/web/api/fetch/index.html b/files/ru/web/api/fetch/index.html new file mode 100644 index 0000000000..788b9c3f69 --- /dev/null +++ b/files/ru/web/api/fetch/index.html @@ -0,0 +1,169 @@ +--- +title: WindowOrWorkerGlobalScope.fetch() +slug: Web/API/fetch +tags: + - Справка + - запрос + - метод +translation_of: Web/API/WindowOrWorkerGlobalScope/fetch +original_slug: Web/API/WindowOrWorkerGlobalScope/fetch +--- +
{{APIRef("Fetch API")}}
+ +

Метод fetch() , относящийся к миксину {{domxref("WindowOrWorkerGlobalScope")}}, запускает процесс извлечения ресурса из сети. Возвращает promise, содержащий {{domxref("Response")}} объект (ответ на запрос).

+ +

WorkerOrGlobalScope относится к {{domxref("Window")}} и {{domxref("WorkerGlobalScope")}} сразу. Это означает, что метод fetch() доступен практически в любом контексте, в котором бы вы не захотели получить ресурсы.

+ +

Промис {{domxref("WindowOrWorkerGlobalScope.fetch","Fetch()")}} завершается {{jsxref("TypeError")}}, если возникает сетевая ошибка, хотя обычно это означает проблему с доступами или аналогичную ей. Для успешного завершения fetch() достаточно удостовериться в том, что промис выполнен и что свойство {{domxref("Response.ok")}} имеет значение true. HTTP статус 404 не является сетевой ошибкой.

+ +

Метод fetch() контролируется директивой connect-src directive of Content Security Policy (политика безопасности контента), а не директивой ресурсов, которые извлекает.

+ +
+

На Заметку: Аргументы метода fetch() идентичны аргументам {{domxref("Request.Request","Request()")}} конструктора.

+
+ +

Синтаксис

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

Аргументы

+ +
+
input
+
Определяет желаемый для получения ресурс. Это может быть: +
    +
  • {{domxref("USVString")}} (строка), содержащая прямую URL ссылку на ресурс. Некоторые браузеры принимают blob: и data: , как схемы.
  • +
  • {{domxref("Request")}} объект (объект ответа).
  • +
+
+
init {{optional_inline}}
+
Объект с опциями, содержащий пользовательские настройки, которые вы желаете применить к запросу. Возможные варианты: +
    +
  • method: Метод запроса, например, GET, POST.
  • +
  • headers: Заголовки, содержащиеся в объекте {{domxref("Headers")}} или в объекте литерале с побитовыми значениями ({{domxref("ByteString")}}).
  • +
  • body: Тело запроса, которое может быть: {{domxref("Blob")}}, {{domxref("BufferSource")}}, {{domxref("FormData")}}, {{domxref("URLSearchParams")}}, или {{domxref("USVString")}} объектами. Обратите внимание, что GET или HEAD запрос не может иметь тела.
  • +
  • mode: Режим, например, cors, no-cors или same-origin.
  • +
  • credentials: Полномочия: omit, same-origin или include. Для автоматической отправки куки для текущего домена, эта опция должна быть указана. Начиная с Chrome 50, это свойство также принимает экземпляр класса {{domxref("FederatedCredential")}} или  {{domxref("PasswordCredential")}}.
  • +
  • cache: Режим кеширования запроса default, no-store, reload, no-cache, force-cache или only-if-cached.
  • +
  • redirect: Режим редиректа: follow (автоматически переадресовывать), error (прерывать перенаправление ошибкой) или manual (управлять перенаправлениями вручную). В Chrome по дефолту стоит follow (ранее, в Chrome 47, стояло manual).
  • +
  • referrer: {{domxref("USVString")}}, определяющая no-referrerclient или a URL. Дефолтное значение - client.
  • +
  • referrerPolicy: Определяет значение HTTP заголовка реферера. Может быть: no-referrer, no-referrer-when-downgrade, origin, origin-when-cross-origin, unsafe-url.
  • +
  • integrity: Содержит значение целостности субресурсов (subresource integrity) запроса (например, sha256-BpfBw7ivV8q2jLiT13fxDYAe2tJllusRSZ273h2nFSE=).
  • +
  • keepalive: Эта опция может быть использована, чтобы разрешить запросу "пережить" страницу. Получение ресурсов с флагом keepalive - это альтернатива {{domxref("Navigator.sendBeacon()")}} API. 
  • +
  • signal: Экземпляр объекта {{domxref("AbortSignal")}}; позволяет коммуницировать с fetch запросом и, если нужно, отменять его с помощью {{domxref("AbortController")}}.
  • +
+
+
+ +

Возвращаемое значение

+ +

{{domxref("Promise")}}, содержащий {{domxref("Response")}} объект (ответ на запрос).

+ +

Исключения

+ + + + + + + + + + + + + + + + + + +
ТипОписание
AbortErrorЗапрос был отменён (используя {{domxref("AbortController.abort()")}}).
TypeErrorНачиная с версии Firefox 43, fetch() завершится ошибкой TypeError, если URL имеет такие полномочия, как http://user:password@example.com.
+ +

Пример

+ +

В нашем Fetch Request примере (см. Fetch Request live) мы создаём новый объект {{domxref("Request")}} (запроса), используя релевантный конструктор, а затем получаем его вызовом fetch(). Так как запрашиваемый ресурс - изображение, для того, чтобы присвоить ему подходящий MIME тип и обработать должным образом, мы применяем к ответу метод {{domxref("Body.blob()")}}, после чего создаём для него Object URL и передаём её в элемент {{htmlelement("img")}}.

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

В нашем Fetch with init then Request примере (см. Fetch Request init live) мы делаем тоже самое, за исключением того, что передаём в качестве аргумента для fetch() объект init:

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

Обратите внимание, что объект init в качестве аргумента можно передать и в конструктор Request для получения аналогичного результата, например:

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

Допустимо использования объекта литерала в качестве headers в init.

+ +
var myInit = { method: 'GET',
+               headers: {
+                   'Content-Type': 'image/jpeg'
+               },
+               mode: 'cors',
+               cache: 'default' };
+
+var 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/ru/web/api/setinterval/index.html b/files/ru/web/api/setinterval/index.html new file mode 100644 index 0000000000..81df340981 --- /dev/null +++ b/files/ru/web/api/setinterval/index.html @@ -0,0 +1,642 @@ +--- +title: WindowOrWorkerGlobalScope.setInterval() +slug: Web/API/setInterval +translation_of: Web/API/WindowOrWorkerGlobalScope/setInterval +original_slug: Web/API/WindowOrWorkerGlobalScope/setInterval +--- +
{{APIRef("HTML DOM")}}
+ +

Метод setInterval() предложен для {{domxref("Window")}} и {{domxref("Worker")}} интерфейсов. Он циклически вызывает функцию или участок кода с фиксированной паузой между каждым вызовом. Уникальный идентификатор intervalID, возвращаемый методом, позволяет впоследствии удалить запущенный setInterval c помощью {{domxref("WindowOrWorkerGlobalScope.clearInterval", "clearInterval()")}}. Метод определён с помощью миксина {{domxref("WindowOrWorkerGlobalScope")}}.

+ +

Синтаксис

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

Параметры

+ +
+
func
+
{{jsxref("function")}} - функция, которая будет вызываться каждые delay миллисекунд. Ожидается, что функция не принимает параметры и ничего не возвращает.
+
code
+
Этот необязательный синтаксис позволяет вам включать строку вместо функции, которая компилируется и выполняется каждые delay миллисекунд. Однако такая форма не рекомендуется по тем же причинам, которые делают {{jsxref("eval", "eval()")}} угрозой безопасности.
+
delay
+
Время в миллисекундах (одна тысячная секунды), на которое таймер выполнит задержку между вызовом функции. Если задано значение меньше 10, то будет использовано число 10. На самом деле задержка может быть больше чем указано, дополнительное объяснение приведено здесь:  {{SectionOnPage("/en-US/docs/Web/API/WindowOrWorkerGlobalScope/setTimeout", "Reasons for delays longer than specified")}}.
+
param1, ..., paramN {{optional_inline}}
+
Дополнительные параметры, передаваемые в функцию func.
+
+ +
+

Примечание: Передача дополнительных аргументов в setInterval() в первом синтаксисе не работает в Internet Explorer 9 и более ранних версиях.Если вы хотите включить эту функцию в этом браузере, вам следует использовать polyfill (смотрите раздел Callback аргументы).

+
+ +

Возвращаемое значение

+ +

Возвращаемый intervalID представляет из себя ненулевое числовое значение, которое идентифицирует таймер, созданный вызовом setInterval(); Это значение может быть передано в {{domxref("WindowOrWorkerGlobalScope.clearInterval()")}} для отмены таймера.

+ +

It may be helpful to be aware that setInterval() and {{domxref("WindowOrWorkerGlobalScope.setTimeout", "setTimeout()")}} share the same pool of IDs, and that clearInterval() and {{domxref("WindowOrWorkerGlobalScope.clearTimeout", "clearTimeout()")}} can technically be used interchangeably. For clarity, however, you should try to always match them to avoid confusion when maintaining your code.

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

Примеры

+ +

Пример 1: Базовый синтаксис

+ +

The following example demonstrates setInterval()'s basic syntax.

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

Пример 2: Чередование двух цветов

+ +

В следующем примере вызывается функция flashtext() раз в секунду, до того момента, как будет нажата кнопка Stop.

+ +
<!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' это тернарный оператор.
+    }
+
+    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: Симуляция пишущей машинки

+ +

The following example simulates typewriter by first clearing and then slowly typing content into the NodeList that matches a specified group of selectors.

+ +
<!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().

+ +

Аргументы колбэк-функции

+ +

As previously discussed, Internet Explorer versions 9 and below do not support the passing of arguments to the callback function in either setTimeout() or setInterval(). The following IE-specific code demonstrates a method for overcoming this limitation.  To use, simply add the following code to the top of your script.

+ +
/*\
+|*|
+|*|  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;
+}
+
+ +

Another possibility is to use an anonymous function to call your callback, although this solution is a bit more expensive. Example:

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

Another possibility is to use function's bind. Example:

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

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

+ +

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

+ +

Проблема с "this"

+ +

When you pass a method to setInterval() or any other function, it is invoked with the wrong this value. This problem is explained in detail in the JavaScript reference.

+ +

Объяснение

+ +

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

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

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

+ +

Возможное решение

+ +

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

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

Новое тестируемое свойство:

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

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

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

MiniDaemon - фреймворк для управления таймерами

+ +

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

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

minidaemon.js

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

Синтаксис

+ +

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

+ +

Описание

+ +

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

+ +

Параметры

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

MiniDaemon instances properties

+ +
+
myDaemon.owner
+
The this object on which is executed the daemon (read/write). It can be an object or null.
+
myDaemon.task
+
The function that is repeatedly invoked (read/write). It is called with three arguments: index (the iterative index of each invocation), length (the number of total invocations assigned to the daemon - finite or Infinity) and backwards (a boolean expressing whether the index is decreasing or not) – see above. If the myDaemon.task function returns a false value the daemon is paused.
+
myDaemon.rate
+
Промежуток времени (в миллисекундах) между каждым вызовом (чтение / запись).
+
myDaemon.length
+
Итоговое количество вызовов. Это может быть положительное целое число или бесконечность Infinity (чтение / запись).
+
+ +

MiniDaemon instances methods

+ +
+
myDaemon.isAtEnd()
+
Возвращает логическое значение (true или false), в зависимости от того, находится ли daemon в начальной / конечной позиции или нет.  
+
myDaemon.synchronize()
+
Synchronize the timer of a started daemon with the time of its invocation.
+
myDaemon.pause()
+
Pauses the daemon.
+
myDaemon.start([reverse])
+
Starts the daemon forward (index of each invocation increasing) or backwards (index decreasing).
+
+ +

MiniDaemon global object methods

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

Пример использования

+ +

Ваша HTML страница:

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

View this example in action

+ +

Примечания

+ +

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

+ +

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

+ +

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

+ +

Ensure that execution duration is shorter than interval frequency

+ +

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

+ +

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

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

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

+ +

Throttling of intervals

+ +

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

+ +

Спецификации

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

Совместимость с браузерами

+ +
+ + +

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

+
+ +

Смотрите также

+ +
    +
  • JavaScript timers
  • +
  • {{domxref("WindowOrWorkerGlobalScope.setTimeout")}}
  • +
  • {{domxref("WindowOrWorkerGlobalScope.clearTimeout")}}
  • +
  • {{domxref("WindowOrWorkerGlobalScope.clearInterval")}}
  • +
  • {{domxref("window.requestAnimationFrame")}}
  • +
  • Daemons management
  • +
+ +
+
+
+ +
+
+
+ +
+

+ +

+
+
+
+
+
diff --git a/files/ru/web/api/settimeout/index.html b/files/ru/web/api/settimeout/index.html new file mode 100644 index 0000000000..d35da11a1c --- /dev/null +++ b/files/ru/web/api/settimeout/index.html @@ -0,0 +1,261 @@ +--- +title: WindowTimers.setTimeout() +slug: Web/API/setTimeout +translation_of: Web/API/WindowOrWorkerGlobalScope/setTimeout +original_slug: Web/API/WindowOrWorkerGlobalScope/setTimeout +--- +
{{ APIRef() }}
+ +

Краткое изложение

+ +

Вызов функции или выполнение фрагмента кода после указанной задержки.

+ +

Синтаксис

+ +
var timeoutID = window.setTimeout(func, [, delay, param1, param2, ...]);
+var timeoutID = window.setTimeout(code [, delay]);
+
+ +

где

+ +
    +
  • timeoutID - это числовой ID, который может быть использован позже с {{domxref("window.clearTimeout()")}}.
  • +
  • func - это функция, которую требуется вызвать после delay миллисекунд.
  • +
  • code - в альтернативном варианте применения это строка, содержащая код, который вы хотите выполнить после delay миллисекунд (использовать этот метод не рекомендуется по тем же причинам, что и eval())
  • +
  • delay  {{optional_inline}} -  задержка в миллисекундах (тысячных долях секунды), после которой будет выполнен вызов функции. Реальная задержка может быть больше; см. {{anch("Notes")}} ниже.
  • +
+ +

Необходимо принять во внимание, что передача дополнительных параметров функции в первом варианте не работает в Internet Explorer 9 и ниже. Для использования этой функциональности в таких браузерах, необходимо использовать код для совместимости (см. раздел Аргументы колбэк-функции).

+ +
Important: Prior to Gecko 13 {{ geckoRelease("13.0") }}, Gecko passed an extra parameter to the callback routine, indicating the "actual lateness" of the timeout in milliseconds. This non-standard parameter is no longer passed.
+ +

Пример

+ +

В следующем примере на веб странице создаются две простые кнопки, к которым привязываются действия setTimeout и clearTimeout. Нажатие на первую кнопку установит таймаут, который вызовет диалоговое окно через две секунды. Также будет сохранён id для clearTimeout. Таймаут также может быть отменён по нажатию на вторую кнопку.

+ +

HTML Content

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

JavaScript Content

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

{{ EmbedLiveSample('Example') }}

+ +

Смотрите также пример clearTimeout().

+ +

Аргументы колбэк-функции

+ +

Если вам нужно передать аргумент в вашу callback функцию, но нужно, чтобы это работало в Internet Explorer 9 и ниже, который не поддерживает передачу дополнительных параметров (ни с setTimeout() или setInterval()), то вы можете прописать специальный код для совместимости с IE, вставив этот код в начало ваших скриптов, который включит функцию передачи стандартных параметров HTML5 в Internet Explorer для обоих таймеров.

+ +
/*\
+|*|
+|*|  IE-specific polyfill which enables the passage of arbitrary arguments to the
+|*|  callback functions of JavaScript timers (HTML5 standard syntax).
+|*|
+|*|  https://developer.mozilla.org/en-US/docs/DOM/window.setInterval
+|*|
+|*|  Syntax:
+|*|  var timeoutID = window.setTimeout(func, delay, [param1, param2, ...]);
+|*|  var timeoutID = window.setTimeout(code, delay);
+|*|  var intervalID = window.setInterval(func, delay[, param1, param2, ...]);
+|*|  var intervalID = window.setInterval(code, delay);
+|*|
+\*/
+
+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;
+}
+
+ +

Правка только для IE

+ +

If you want a completely unobtrusive hack for every other mobile or desktop browser, including IE 9 and below, you can either use JavaScript conditional comments:

+ +
/*@cc_on
+  // conditional IE < 9 only fix
+  @if (@_jscript_version <= 6)
+  (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.apply(this,a)},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.apply(this,a)},t)}
+});
+</script><![endif]-->
+
+ +

Another possibility is to use an anonymous function to call your callback, but this solution is a bit more expensive. Example:

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

Yet another possibility is to use function's bind. Example:

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

Проблема с "this"

+ +

Когда вы передаёте метод в setTimeout() (или в любую другую функцию, если на то пошло), то вызов будет осуществлён с неправильным значением this. Эта проблема разъясняется детально в JavaScript reference.

+ +

Объяснение

+ +

Code executed by setTimeout() is run in a separate execution context to the function from which it was called. As a consequence, the this keyword for the called function will be set to the window (or global) object; it will not be the same as the this value for the function that called setTimeout. See the following example:

+ +
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
+// let's try to pass the 'this' 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
+ +

Как видите, нет способов передать объект this в колбэк-функцию..

+ +

Возможное решение

+ +

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

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

Новая тестируемая особенность:

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

Это не нативные решения ad hoc для этой проблемы.

+ +
Note: JavaScript 1.8.5 introduces the Function.prototype.bind() method, which lets you specify the value that should be used as this for all calls to a given function. This lets you easily bypass problems where it's unclear what this will be, depending on the context from which your function was called.
+ +

Замечания

+ +

Отложенное выполнение кода можно отменить, используя window.clearTimeout(). Если функция должна вызываться неоднократно (например, каждые N миллисекунд), необходимо использовать window.setInterval().

+ +

Важно заметить, что функция или код не могут быть выполнены, пока не завершится поток, вызвавший setTimeout().

+ +

Passing string literals

+ +

Передача строки вместо функции в setTimeout() сопряжена с теми же опасностями, что и использование eval.

+ +
// Правильно
+window.setTimeout(function() {
+    alert("Hello World!");
+}, 500);
+
+// Неправильно
+window.setTimeout("alert(\"Hello World!\");", 500);
+
+
+ +

String literals are evaluated in the global context, so local symbols in the context where setTimeout() was called will not be available when the string is evaluated as code.

+ +

Минимальная/ максимальная задержка и вложенность таймаута

+ +

Historically browsers implement setTimeout() "clamping": successive setTimeout() calls with delay smaller than the "minimum delay" limit are forced to use at least the minimum delay. The minimum delay, DOM_MIN_TIMEOUT_VALUE, is 4 ms (stored in a preference in Firefox: dom.min_timeout_value), with a DOM_CLAMP_TIMEOUT_NESTING_LEVEL of 5ms.

+ +

In fact, 4ms is specified by the HTML5 spec and is consistent across browsers released in 2010 and onward. Prior to {{ geckoRelease("5.0") }}, the minimum timeout value for nested timeouts was 10 ms.

+ +

In addition to "clamping", the timeout can also fire later when the page (or the OS/browser itself) is busy with other tasks.

+ +

To implement a 0 ms timeout in a modern browser, you can use {{ domxref("window.postMessage()") }} as described here.

+ +

Browsers including Internet Explorer, Chrome, Safari, and Firefox store the delay as a 32-bit signed Integer internally. This causes an Integer overflow when using delays larger than 2147483647, resulting in the timeout being executed immediately.

+ +

Неактивные вкладки

+ +

In {{ geckoRelease("5.0") }} and Chrome 11, timeouts are clamped to firing no more often than once per second (1000ms) in inactive tabs; see {{ bug(633421) }} for more information about this in Mozilla or crbug.com/66078 for details about this in Chrome.

+ +

Совместимость с браузерами

+ +

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

+ +

Спецификация

+ +

Part of DOM level 0, as specified in HTML5.

+ +

Также интересно

+ + diff --git a/files/ru/web/api/windoworworkerglobalscope/atob/index.html b/files/ru/web/api/windoworworkerglobalscope/atob/index.html deleted file mode 100644 index 689abf3503..0000000000 --- a/files/ru/web/api/windoworworkerglobalscope/atob/index.html +++ /dev/null @@ -1,70 +0,0 @@ ---- -title: WindowOrWorkerGlobalScope.atob() -slug: Web/API/WindowOrWorkerGlobalScope/atob -translation_of: Web/API/WindowOrWorkerGlobalScope/atob ---- -
{{APIRef("HTML DOM")}}
- -

Функция WindowOrWorkerGlobalScope.atob() декодирует строку данных, которая была закодирована с использованием  base-64. Вы можете использовать метод {{domxref("WindowOrWorkerGlobalScope.btoa","btoa()")}}, чтобы декодировать и передать данные, которые в исходном виде могут вызвать проблемы  передачи, затем отправить их, и использовать метод atob() чтобы декодировать даны снова. Например, вы можете закодировать, передать, и декодировать управляющие символы, такие как ASCII значения от 0 до 31.

- -

В случаях использования с Unicode или UTF-8 строками, смотрите this note at Base64 encoding and decoding и this note at btoa().

- -

Синтаксис

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

Throws

- -

Выбрасывает {{jsxref("DOMException")}}, если длина переданной строки не кратна 4.

- -

Пример

- -
var encodedData = window.btoa('Hello, world'); // кодирует строку
-var decodedData = window.atob(encodedData); // декодирует строку
- -

Спецификации

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
СпецификацияСтатусКомментарий
{{SpecName('HTML WHATWG', 'webappapis.html#dom-btoa', 'WindowOrWorkerGlobalScope.atob()')}}{{Spec2('HTML WHATWG')}}Method moved to the WindowOrWorkerGlobalScope mixin in the latest spec.
{{SpecName('HTML WHATWG', '#dom-windowbase64-atob', 'WindowBase64.atob()')}}{{Spec2('HTML WHATWG')}}No change since the latest snapshot, {{SpecName("HTML5.1")}}.
{{SpecName('HTML5.1', '#dom-windowbase64-atob', 'WindowBase64.atob()')}}{{Spec2('HTML5.1')}}Snapshot of {{SpecName("HTML WHATWG")}}. No change.
{{SpecName("HTML5 W3C", "#dom-windowbase64-atob", "WindowBase64.atob()")}}{{Spec2('HTML5 W3C')}}Snapshot of {{SpecName("HTML WHATWG")}}. Creation of WindowBase64 (properties were on the target before it).
- -

Совместимость с браузерами

- -

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

- -

Смотрите также

- - diff --git a/files/ru/web/api/windoworworkerglobalscope/btoa/index.html b/files/ru/web/api/windoworworkerglobalscope/btoa/index.html deleted file mode 100644 index 24f0c7ab38..0000000000 --- a/files/ru/web/api/windoworworkerglobalscope/btoa/index.html +++ /dev/null @@ -1,94 +0,0 @@ ---- -title: WindowBase64.btoa() -slug: Web/API/WindowOrWorkerGlobalScope/btoa -translation_of: Web/API/WindowOrWorkerGlobalScope/btoa -original_slug: Web/API/WindowBase64/btoa ---- -
{{APIRef("HTML DOM")}}
- -

Создаёт ASCII строку закодированную в base-64 из "строки" бинарных данных.

- -

Будьте внимательней этот способ не подходит для Unicode строк! Описание работы с Unicode в секции ниже.

- -

Синтаксис

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

Пример

- -
var encodedData = window.btoa("Hello, world"); // encode a string
-var decodedData = window.atob(encodedData); // decode the string
-
- -

Замечания

- -

Вы можете воспользоваться этим способом, чтобы избежать проблем при передаче данных через сетевое соединение. Для этого нужно перекодировать данные в base64 и отправить их, и на другой стороне с помощью метода {{domxref("WindowBase64.atob","window.atob()")}} декодировать полученные данные в исходный вид. Например, вы можете перекодировать управляющие символы ASCII с 0 до 31.

- -

btoa() также доступна для XPCOM компонентов реализованных в JavaScript, даже если window не является глобальным объектом в компонентах.

- -

Строки Юникод

- -

В большинстве браузеров, вызов window.btoa() на Unicode строке выбросит исключение Character Out Of Range (Символ вне допустимого диапазона).

- -

Чтобы избежать этого, воспользуйтесь паттерном, предложенным Johan Sundström:

- -
function utf8_to_b64(str) {
-    return window.btoa(unescape(encodeURIComponent(str)));
-}
-
-function b64_to_utf8(str) {
-    return decodeURIComponent(escape(window.atob(str)));
-}
-
-// Usage:
-utf8_to_b64('✓ à la mode'); // JTI1dTI3MTMlMjUyMCUyNUUwJTI1MjBsYSUyNTIwbW9kZQ==
-b64_to_utf8('JTI1dTI3MTMlMjUyMCUyNUUwJTI1MjBsYSUyNTIwbW9kZQ=='); // "✓ à la mode"
-
-utf8_to_b64('I \u2661 Unicode!'); // SSUyNTIwJTI1dTI2NjElMjUyMFVuaWNvZGUlMjUyMQ==
-b64_to_utf8('SSUyNTIwJTI1dTI2NjElMjUyMFVuaWNvZGUlMjUyMQ=='); // "I ♡ Unicode!"
-
-
- -

Более правильный и производительный способ - это конвертировать DOMString в UTF-8 строку передав typed arrays. Как это сделать узнать можно здесь в этом параграфе.

- -

Спецификации

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

Совместимость браузеров

- -

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

- -

Смотрите также

- - diff --git a/files/ru/web/api/windoworworkerglobalscope/caches/index.html b/files/ru/web/api/windoworworkerglobalscope/caches/index.html deleted file mode 100644 index 107d43f6a4..0000000000 --- a/files/ru/web/api/windoworworkerglobalscope/caches/index.html +++ /dev/null @@ -1,79 +0,0 @@ ---- -title: WindowOrWorkerGlobalScope.caches -slug: Web/API/WindowOrWorkerGlobalScope/caches -translation_of: Web/API/WindowOrWorkerGlobalScope/caches ---- -
{{APIRef()}}{{SeeCompatTable}}
- -

caches {{domxref("WindowOrWorkerGlobalScope")}}  свойство только для чтения интерфейса возвращающее  объект ассоциированный с текущим контекстом {{domxref("CacheStorage")}}.

- -

Этот объект реализует такую  функциональность как строгое соответствие для офлайн-использования  и генерирование пользовательских ответов на запросы.

- -

Синтаксис

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

Значение

- -

Возвращает значение {{domxref("CacheStorage")}} .

- -

Пример

- -

Данный пример показывает как надо использовать кеш в контексте service worker для хранения в автономном режиме

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

Спецификации

- - - - - - - - - - - - - - - - - - - -
SpecificationStatusComment
{{SpecName('Service Workers', '#self-caches', 'caches')}}{{Spec2('Service Workers')}}Объявлена частичная поддержка в новейшей спецификации WindowOrWorkerGlobalScope.
{{SpecName('Service Workers')}}{{Spec2('Service Workers')}}Начальное определение.
- -

Совместимость с браузерами

- - - -

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

- -

Также смотрите

- - diff --git a/files/ru/web/api/windoworworkerglobalscope/cleartimeout/index.html b/files/ru/web/api/windoworworkerglobalscope/cleartimeout/index.html deleted file mode 100644 index aeedb7435c..0000000000 --- a/files/ru/web/api/windoworworkerglobalscope/cleartimeout/index.html +++ /dev/null @@ -1,94 +0,0 @@ ---- -title: WindowOrWorkerGlobalScope.clearTimeout() -slug: Web/API/WindowOrWorkerGlobalScope/clearTimeout -translation_of: Web/API/WindowOrWorkerGlobalScope/clearTimeout ---- -
{{APIRef("HTML DOM")}}
- -

clearTimeout() метод {{domxref("WindowOrWorkerGlobalScope")}} отменяет таймаут, ранее установленный вызовом {{domxref("WindowOrWorkerGlobalScope.setTimeout", "setTimeout()")}}.

- -

Синтаксис

- -
scope.clearTimeout(timeoutID)
-
- -

Параметры

- -
-
timeoutID
-
-
Идентификатор таймаута, который вы хотите отменить. Этот идентификатор был возвращён соответствующим вызовом setTimeout().
-
- -

It's worth noting that the pool of IDs used by {{domxref("WindowOrWorkerGlobalScope.setTimeout", "setTimeout()")}} and {{domxref("WindowOrWorkerGlobalScope.setInterval", "setInterval()")}} are shared, which means you can technically use clearTimeout() and {{domxref("WindowOrWorkerGlobalScope.clearInterval", "clearInterval()")}} interchangeably. However, for clarity, you should avoid doing so.

- -

Пример использования:

- -

Запустите приведённый ниже скрипт в контакте веб-страницы и кликните один раз. Вы увидите всплывающее сообщение через 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(); };
-
- -

Примечания

- -

Передача недействительного ID clearTimeout() ни к чему не приведёт. Исключение не создается.

- -

Спецификация

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

Совместимость с браузером

- - - -

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

- -

Смотрите также

- -
    -
  • {{domxref("WindowOrWorkerGlobalScope.setTimeout()")}}
  • -
  • {{domxref("WindowOrWorkerGlobalScope.setInterval()")}}
  • -
  • {{domxref("WindowOrWorkerGlobalScope.clearInterval()")}}
  • -
  • {{domxref("Window.requestAnimationFrame()")}}
  • -
  • Daemons management
  • -
diff --git a/files/ru/web/api/windoworworkerglobalscope/fetch/index.html b/files/ru/web/api/windoworworkerglobalscope/fetch/index.html deleted file mode 100644 index 22b188e0bd..0000000000 --- a/files/ru/web/api/windoworworkerglobalscope/fetch/index.html +++ /dev/null @@ -1,168 +0,0 @@ ---- -title: WindowOrWorkerGlobalScope.fetch() -slug: Web/API/WindowOrWorkerGlobalScope/fetch -tags: - - Справка - - запрос - - метод -translation_of: Web/API/WindowOrWorkerGlobalScope/fetch ---- -
{{APIRef("Fetch API")}}
- -

Метод fetch() , относящийся к миксину {{domxref("WindowOrWorkerGlobalScope")}}, запускает процесс извлечения ресурса из сети. Возвращает promise, содержащий {{domxref("Response")}} объект (ответ на запрос).

- -

WorkerOrGlobalScope относится к {{domxref("Window")}} и {{domxref("WorkerGlobalScope")}} сразу. Это означает, что метод fetch() доступен практически в любом контексте, в котором бы вы не захотели получить ресурсы.

- -

Промис {{domxref("WindowOrWorkerGlobalScope.fetch","Fetch()")}} завершается {{jsxref("TypeError")}}, если возникает сетевая ошибка, хотя обычно это означает проблему с доступами или аналогичную ей. Для успешного завершения fetch() достаточно удостовериться в том, что промис выполнен и что свойство {{domxref("Response.ok")}} имеет значение true. HTTP статус 404 не является сетевой ошибкой.

- -

Метод fetch() контролируется директивой connect-src directive of Content Security Policy (политика безопасности контента), а не директивой ресурсов, которые извлекает.

- -
-

На Заметку: Аргументы метода fetch() идентичны аргументам {{domxref("Request.Request","Request()")}} конструктора.

-
- -

Синтаксис

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

Аргументы

- -
-
input
-
Определяет желаемый для получения ресурс. Это может быть: -
    -
  • {{domxref("USVString")}} (строка), содержащая прямую URL ссылку на ресурс. Некоторые браузеры принимают blob: и data: , как схемы.
  • -
  • {{domxref("Request")}} объект (объект ответа).
  • -
-
-
init {{optional_inline}}
-
Объект с опциями, содержащий пользовательские настройки, которые вы желаете применить к запросу. Возможные варианты: -
    -
  • method: Метод запроса, например, GET, POST.
  • -
  • headers: Заголовки, содержащиеся в объекте {{domxref("Headers")}} или в объекте литерале с побитовыми значениями ({{domxref("ByteString")}}).
  • -
  • body: Тело запроса, которое может быть: {{domxref("Blob")}}, {{domxref("BufferSource")}}, {{domxref("FormData")}}, {{domxref("URLSearchParams")}}, или {{domxref("USVString")}} объектами. Обратите внимание, что GET или HEAD запрос не может иметь тела.
  • -
  • mode: Режим, например, cors, no-cors или same-origin.
  • -
  • credentials: Полномочия: omit, same-origin или include. Для автоматической отправки куки для текущего домена, эта опция должна быть указана. Начиная с Chrome 50, это свойство также принимает экземпляр класса {{domxref("FederatedCredential")}} или  {{domxref("PasswordCredential")}}.
  • -
  • cache: Режим кеширования запроса default, no-store, reload, no-cache, force-cache или only-if-cached.
  • -
  • redirect: Режим редиректа: follow (автоматически переадресовывать), error (прерывать перенаправление ошибкой) или manual (управлять перенаправлениями вручную). В Chrome по дефолту стоит follow (ранее, в Chrome 47, стояло manual).
  • -
  • referrer: {{domxref("USVString")}}, определяющая no-referrerclient или a URL. Дефолтное значение - client.
  • -
  • referrerPolicy: Определяет значение HTTP заголовка реферера. Может быть: no-referrer, no-referrer-when-downgrade, origin, origin-when-cross-origin, unsafe-url.
  • -
  • integrity: Содержит значение целостности субресурсов (subresource integrity) запроса (например, sha256-BpfBw7ivV8q2jLiT13fxDYAe2tJllusRSZ273h2nFSE=).
  • -
  • keepalive: Эта опция может быть использована, чтобы разрешить запросу "пережить" страницу. Получение ресурсов с флагом keepalive - это альтернатива {{domxref("Navigator.sendBeacon()")}} API. 
  • -
  • signal: Экземпляр объекта {{domxref("AbortSignal")}}; позволяет коммуницировать с fetch запросом и, если нужно, отменять его с помощью {{domxref("AbortController")}}.
  • -
-
-
- -

Возвращаемое значение

- -

{{domxref("Promise")}}, содержащий {{domxref("Response")}} объект (ответ на запрос).

- -

Исключения

- - - - - - - - - - - - - - - - - - -
ТипОписание
AbortErrorЗапрос был отменён (используя {{domxref("AbortController.abort()")}}).
TypeErrorНачиная с версии Firefox 43, fetch() завершится ошибкой TypeError, если URL имеет такие полномочия, как http://user:password@example.com.
- -

Пример

- -

В нашем Fetch Request примере (см. Fetch Request live) мы создаём новый объект {{domxref("Request")}} (запроса), используя релевантный конструктор, а затем получаем его вызовом fetch(). Так как запрашиваемый ресурс - изображение, для того, чтобы присвоить ему подходящий MIME тип и обработать должным образом, мы применяем к ответу метод {{domxref("Body.blob()")}}, после чего создаём для него Object URL и передаём её в элемент {{htmlelement("img")}}.

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

В нашем Fetch with init then Request примере (см. Fetch Request init live) мы делаем тоже самое, за исключением того, что передаём в качестве аргумента для fetch() объект init:

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

Обратите внимание, что объект init в качестве аргумента можно передать и в конструктор Request для получения аналогичного результата, например:

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

Допустимо использования объекта литерала в качестве headers в init.

- -
var myInit = { method: 'GET',
-               headers: {
-                   'Content-Type': 'image/jpeg'
-               },
-               mode: 'cors',
-               cache: 'default' };
-
-var 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/ru/web/api/windoworworkerglobalscope/setinterval/index.html b/files/ru/web/api/windoworworkerglobalscope/setinterval/index.html deleted file mode 100644 index c77c422bf1..0000000000 --- a/files/ru/web/api/windoworworkerglobalscope/setinterval/index.html +++ /dev/null @@ -1,641 +0,0 @@ ---- -title: WindowOrWorkerGlobalScope.setInterval() -slug: Web/API/WindowOrWorkerGlobalScope/setInterval -translation_of: Web/API/WindowOrWorkerGlobalScope/setInterval ---- -
{{APIRef("HTML DOM")}}
- -

Метод setInterval() предложен для {{domxref("Window")}} и {{domxref("Worker")}} интерфейсов. Он циклически вызывает функцию или участок кода с фиксированной паузой между каждым вызовом. Уникальный идентификатор intervalID, возвращаемый методом, позволяет впоследствии удалить запущенный setInterval c помощью {{domxref("WindowOrWorkerGlobalScope.clearInterval", "clearInterval()")}}. Метод определён с помощью миксина {{domxref("WindowOrWorkerGlobalScope")}}.

- -

Синтаксис

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

Параметры

- -
-
func
-
{{jsxref("function")}} - функция, которая будет вызываться каждые delay миллисекунд. Ожидается, что функция не принимает параметры и ничего не возвращает.
-
code
-
Этот необязательный синтаксис позволяет вам включать строку вместо функции, которая компилируется и выполняется каждые delay миллисекунд. Однако такая форма не рекомендуется по тем же причинам, которые делают {{jsxref("eval", "eval()")}} угрозой безопасности.
-
delay
-
Время в миллисекундах (одна тысячная секунды), на которое таймер выполнит задержку между вызовом функции. Если задано значение меньше 10, то будет использовано число 10. На самом деле задержка может быть больше чем указано, дополнительное объяснение приведено здесь:  {{SectionOnPage("/en-US/docs/Web/API/WindowOrWorkerGlobalScope/setTimeout", "Reasons for delays longer than specified")}}.
-
param1, ..., paramN {{optional_inline}}
-
Дополнительные параметры, передаваемые в функцию func.
-
- -
-

Примечание: Передача дополнительных аргументов в setInterval() в первом синтаксисе не работает в Internet Explorer 9 и более ранних версиях.Если вы хотите включить эту функцию в этом браузере, вам следует использовать polyfill (смотрите раздел Callback аргументы).

-
- -

Возвращаемое значение

- -

Возвращаемый intervalID представляет из себя ненулевое числовое значение, которое идентифицирует таймер, созданный вызовом setInterval(); Это значение может быть передано в {{domxref("WindowOrWorkerGlobalScope.clearInterval()")}} для отмены таймера.

- -

It may be helpful to be aware that setInterval() and {{domxref("WindowOrWorkerGlobalScope.setTimeout", "setTimeout()")}} share the same pool of IDs, and that clearInterval() and {{domxref("WindowOrWorkerGlobalScope.clearTimeout", "clearTimeout()")}} can technically be used interchangeably. For clarity, however, you should try to always match them to avoid confusion when maintaining your code.

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

Примеры

- -

Пример 1: Базовый синтаксис

- -

The following example demonstrates setInterval()'s basic syntax.

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

Пример 2: Чередование двух цветов

- -

В следующем примере вызывается функция flashtext() раз в секунду, до того момента, как будет нажата кнопка Stop.

- -
<!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' это тернарный оператор.
-    }
-
-    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: Симуляция пишущей машинки

- -

The following example simulates typewriter by first clearing and then slowly typing content into the NodeList that matches a specified group of selectors.

- -
<!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().

- -

Аргументы колбэк-функции

- -

As previously discussed, Internet Explorer versions 9 and below do not support the passing of arguments to the callback function in either setTimeout() or setInterval(). The following IE-specific code demonstrates a method for overcoming this limitation.  To use, simply add the following code to the top of your script.

- -
/*\
-|*|
-|*|  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;
-}
-
- -

Another possibility is to use an anonymous function to call your callback, although this solution is a bit more expensive. Example:

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

Another possibility is to use function's bind. Example:

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

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

- -

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

- -

Проблема с "this"

- -

When you pass a method to setInterval() or any other function, it is invoked with the wrong this value. This problem is explained in detail in the JavaScript reference.

- -

Объяснение

- -

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

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

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

- -

Возможное решение

- -

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

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

Новое тестируемое свойство:

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

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

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

MiniDaemon - фреймворк для управления таймерами

- -

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

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

minidaemon.js

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

Синтаксис

- -

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

- -

Описание

- -

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

- -

Параметры

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

MiniDaemon instances properties

- -
-
myDaemon.owner
-
The this object on which is executed the daemon (read/write). It can be an object or null.
-
myDaemon.task
-
The function that is repeatedly invoked (read/write). It is called with three arguments: index (the iterative index of each invocation), length (the number of total invocations assigned to the daemon - finite or Infinity) and backwards (a boolean expressing whether the index is decreasing or not) – see above. If the myDaemon.task function returns a false value the daemon is paused.
-
myDaemon.rate
-
Промежуток времени (в миллисекундах) между каждым вызовом (чтение / запись).
-
myDaemon.length
-
Итоговое количество вызовов. Это может быть положительное целое число или бесконечность Infinity (чтение / запись).
-
- -

MiniDaemon instances methods

- -
-
myDaemon.isAtEnd()
-
Возвращает логическое значение (true или false), в зависимости от того, находится ли daemon в начальной / конечной позиции или нет.  
-
myDaemon.synchronize()
-
Synchronize the timer of a started daemon with the time of its invocation.
-
myDaemon.pause()
-
Pauses the daemon.
-
myDaemon.start([reverse])
-
Starts the daemon forward (index of each invocation increasing) or backwards (index decreasing).
-
- -

MiniDaemon global object methods

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

Пример использования

- -

Ваша HTML страница:

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

View this example in action

- -

Примечания

- -

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

- -

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

- -

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

- -

Ensure that execution duration is shorter than interval frequency

- -

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

- -

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

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

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

- -

Throttling of intervals

- -

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

- -

Спецификации

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

Совместимость с браузерами

- -
- - -

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

-
- -

Смотрите также

- -
    -
  • JavaScript timers
  • -
  • {{domxref("WindowOrWorkerGlobalScope.setTimeout")}}
  • -
  • {{domxref("WindowOrWorkerGlobalScope.clearTimeout")}}
  • -
  • {{domxref("WindowOrWorkerGlobalScope.clearInterval")}}
  • -
  • {{domxref("window.requestAnimationFrame")}}
  • -
  • Daemons management
  • -
- -
-
-
- -
-
-
- -
-

- -

-
-
-
-
-
diff --git a/files/ru/web/api/windoworworkerglobalscope/settimeout/index.html b/files/ru/web/api/windoworworkerglobalscope/settimeout/index.html deleted file mode 100644 index dbc08996a2..0000000000 --- a/files/ru/web/api/windoworworkerglobalscope/settimeout/index.html +++ /dev/null @@ -1,261 +0,0 @@ ---- -title: WindowTimers.setTimeout() -slug: Web/API/WindowOrWorkerGlobalScope/setTimeout -translation_of: Web/API/WindowOrWorkerGlobalScope/setTimeout -original_slug: Web/API/WindowTimers/setTimeout ---- -
{{ APIRef() }}
- -

Краткое изложение

- -

Вызов функции или выполнение фрагмента кода после указанной задержки.

- -

Синтаксис

- -
var timeoutID = window.setTimeout(func, [, delay, param1, param2, ...]);
-var timeoutID = window.setTimeout(code [, delay]);
-
- -

где

- -
    -
  • timeoutID - это числовой ID, который может быть использован позже с {{domxref("window.clearTimeout()")}}.
  • -
  • func - это функция, которую требуется вызвать после delay миллисекунд.
  • -
  • code - в альтернативном варианте применения это строка, содержащая код, который вы хотите выполнить после delay миллисекунд (использовать этот метод не рекомендуется по тем же причинам, что и eval())
  • -
  • delay  {{optional_inline}} -  задержка в миллисекундах (тысячных долях секунды), после которой будет выполнен вызов функции. Реальная задержка может быть больше; см. {{anch("Notes")}} ниже.
  • -
- -

Необходимо принять во внимание, что передача дополнительных параметров функции в первом варианте не работает в Internet Explorer 9 и ниже. Для использования этой функциональности в таких браузерах, необходимо использовать код для совместимости (см. раздел Аргументы колбэк-функции).

- -
Important: Prior to Gecko 13 {{ geckoRelease("13.0") }}, Gecko passed an extra parameter to the callback routine, indicating the "actual lateness" of the timeout in milliseconds. This non-standard parameter is no longer passed.
- -

Пример

- -

В следующем примере на веб странице создаются две простые кнопки, к которым привязываются действия setTimeout и clearTimeout. Нажатие на первую кнопку установит таймаут, который вызовет диалоговое окно через две секунды. Также будет сохранён id для clearTimeout. Таймаут также может быть отменён по нажатию на вторую кнопку.

- -

HTML Content

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

JavaScript Content

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

{{ EmbedLiveSample('Example') }}

- -

Смотрите также пример clearTimeout().

- -

Аргументы колбэк-функции

- -

Если вам нужно передать аргумент в вашу callback функцию, но нужно, чтобы это работало в Internet Explorer 9 и ниже, который не поддерживает передачу дополнительных параметров (ни с setTimeout() или setInterval()), то вы можете прописать специальный код для совместимости с IE, вставив этот код в начало ваших скриптов, который включит функцию передачи стандартных параметров HTML5 в Internet Explorer для обоих таймеров.

- -
/*\
-|*|
-|*|  IE-specific polyfill which enables the passage of arbitrary arguments to the
-|*|  callback functions of JavaScript timers (HTML5 standard syntax).
-|*|
-|*|  https://developer.mozilla.org/en-US/docs/DOM/window.setInterval
-|*|
-|*|  Syntax:
-|*|  var timeoutID = window.setTimeout(func, delay, [param1, param2, ...]);
-|*|  var timeoutID = window.setTimeout(code, delay);
-|*|  var intervalID = window.setInterval(func, delay[, param1, param2, ...]);
-|*|  var intervalID = window.setInterval(code, delay);
-|*|
-\*/
-
-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;
-}
-
- -

Правка только для IE

- -

If you want a completely unobtrusive hack for every other mobile or desktop browser, including IE 9 and below, you can either use JavaScript conditional comments:

- -
/*@cc_on
-  // conditional IE < 9 only fix
-  @if (@_jscript_version <= 6)
-  (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.apply(this,a)},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.apply(this,a)},t)}
-});
-</script><![endif]-->
-
- -

Another possibility is to use an anonymous function to call your callback, but this solution is a bit more expensive. Example:

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

Yet another possibility is to use function's bind. Example:

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

Проблема с "this"

- -

Когда вы передаёте метод в setTimeout() (или в любую другую функцию, если на то пошло), то вызов будет осуществлён с неправильным значением this. Эта проблема разъясняется детально в JavaScript reference.

- -

Объяснение

- -

Code executed by setTimeout() is run in a separate execution context to the function from which it was called. As a consequence, the this keyword for the called function will be set to the window (or global) object; it will not be the same as the this value for the function that called setTimeout. See the following example:

- -
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
-// let's try to pass the 'this' 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
- -

Как видите, нет способов передать объект this в колбэк-функцию..

- -

Возможное решение

- -

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

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

Новая тестируемая особенность:

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

Это не нативные решения ad hoc для этой проблемы.

- -
Note: JavaScript 1.8.5 introduces the Function.prototype.bind() method, which lets you specify the value that should be used as this for all calls to a given function. This lets you easily bypass problems where it's unclear what this will be, depending on the context from which your function was called.
- -

Замечания

- -

Отложенное выполнение кода можно отменить, используя window.clearTimeout(). Если функция должна вызываться неоднократно (например, каждые N миллисекунд), необходимо использовать window.setInterval().

- -

Важно заметить, что функция или код не могут быть выполнены, пока не завершится поток, вызвавший setTimeout().

- -

Passing string literals

- -

Передача строки вместо функции в setTimeout() сопряжена с теми же опасностями, что и использование eval.

- -
// Правильно
-window.setTimeout(function() {
-    alert("Hello World!");
-}, 500);
-
-// Неправильно
-window.setTimeout("alert(\"Hello World!\");", 500);
-
-
- -

String literals are evaluated in the global context, so local symbols in the context where setTimeout() was called will not be available when the string is evaluated as code.

- -

Минимальная/ максимальная задержка и вложенность таймаута

- -

Historically browsers implement setTimeout() "clamping": successive setTimeout() calls with delay smaller than the "minimum delay" limit are forced to use at least the minimum delay. The minimum delay, DOM_MIN_TIMEOUT_VALUE, is 4 ms (stored in a preference in Firefox: dom.min_timeout_value), with a DOM_CLAMP_TIMEOUT_NESTING_LEVEL of 5ms.

- -

In fact, 4ms is specified by the HTML5 spec and is consistent across browsers released in 2010 and onward. Prior to {{ geckoRelease("5.0") }}, the minimum timeout value for nested timeouts was 10 ms.

- -

In addition to "clamping", the timeout can also fire later when the page (or the OS/browser itself) is busy with other tasks.

- -

To implement a 0 ms timeout in a modern browser, you can use {{ domxref("window.postMessage()") }} as described here.

- -

Browsers including Internet Explorer, Chrome, Safari, and Firefox store the delay as a 32-bit signed Integer internally. This causes an Integer overflow when using delays larger than 2147483647, resulting in the timeout being executed immediately.

- -

Неактивные вкладки

- -

In {{ geckoRelease("5.0") }} and Chrome 11, timeouts are clamped to firing no more often than once per second (1000ms) in inactive tabs; see {{ bug(633421) }} for more information about this in Mozilla or crbug.com/66078 for details about this in Chrome.

- -

Совместимость с браузерами

- -

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

- -

Спецификация

- -

Part of DOM level 0, as specified in HTML5.

- -

Также интересно

- - diff --git a/files/zh-cn/_redirects.txt b/files/zh-cn/_redirects.txt index 3e3a29ee8d..f625f0a1c0 100644 --- a/files/zh-cn/_redirects.txt +++ b/files/zh-cn/_redirects.txt @@ -432,11 +432,11 @@ /zh-CN/docs/DOM/window.URL.revokeObjectURL /zh-CN/docs/Web/API/URL/revokeObjectURL /zh-CN/docs/DOM/window.alert /zh-CN/docs/Web/API/Window/alert /zh-CN/docs/DOM/window.applicationCache /zh-CN/docs/Web/API/Window/applicationCache -/zh-CN/docs/DOM/window.atob /zh-CN/docs/Web/API/WindowOrWorkerGlobalScope/atob -/zh-CN/docs/DOM/window.btoa /zh-CN/docs/Web/API/WindowOrWorkerGlobalScope/btoa +/zh-CN/docs/DOM/window.atob /zh-CN/docs/Web/API/atob +/zh-CN/docs/DOM/window.btoa /zh-CN/docs/Web/API/btoa /zh-CN/docs/DOM/window.cancelAnimationFrame /zh-CN/docs/Web/API/Window/cancelAnimationFrame /zh-CN/docs/DOM/window.clearImmediate /zh-CN/docs/Web/API/Window/clearImmediate -/zh-CN/docs/DOM/window.clearInterval /zh-CN/docs/Web/API/WindowOrWorkerGlobalScope/clearInterval +/zh-CN/docs/DOM/window.clearInterval /zh-CN/docs/Web/API/clearInterval /zh-CN/docs/DOM/window.close /zh-CN/docs/Web/API/Window/close /zh-CN/docs/DOM/window.content /zh-CN/docs/Web/API/Window/content /zh-CN/docs/DOM/window.document /zh-CN/docs/Web/API/Window/document @@ -475,9 +475,9 @@ /zh-CN/docs/DOM/window.requestAnimationFrame /zh-CN/docs/Web/API/Window/requestAnimationFrame /zh-CN/docs/DOM/window.scrollByPages /zh-CN/docs/Web/API/Window/scrollByPages /zh-CN/docs/DOM/window.setImmediate /zh-CN/docs/Web/API/Window/setImmediate -/zh-CN/docs/DOM/window.setInterval /zh-CN/docs/Web/API/WindowOrWorkerGlobalScope/setInterval -/zh-CN/docs/DOM/window.setTimeout /zh-CN/docs/Web/API/WindowOrWorkerGlobalScope/setTimeout -/zh-CN/docs/DOM/window.setTimeout12 /zh-CN/docs/Web/API/WindowOrWorkerGlobalScope/setTimeout +/zh-CN/docs/DOM/window.setInterval /zh-CN/docs/Web/API/setInterval +/zh-CN/docs/DOM/window.setTimeout /zh-CN/docs/Web/API/setTimeout +/zh-CN/docs/DOM/window.setTimeout12 /zh-CN/docs/Web/API/setTimeout /zh-CN/docs/DOM/文件系统API的基本概念 /zh-CN/docs/Web/API/File_and_Directory_Entries_API/Introduction /zh-CN/docs/DOM:HTMLDocument /zh-CN/docs/Web/API/HTMLDocument /zh-CN/docs/DOM:XMLDocument /zh-CN/docs/Web/API/XMLDocument @@ -1349,7 +1349,7 @@ /zh-CN/docs/Web/API/GlobalEventHandlers/动画效果 /zh-CN/docs/Web/API/GlobalEventHandlers/onanimationend /zh-CN/docs/Web/API/GlobalEventHandlers/时长改变 /zh-CN/docs/Web/API/GlobalEventHandlers/ondurationchange /zh-CN/docs/Web/API/GlobalFetch /zh-CN/docs/Web/API/WindowOrWorkerGlobalScope -/zh-CN/docs/Web/API/GlobalFetch/fetch /zh-CN/docs/Web/API/WindowOrWorkerGlobalScope/fetch +/zh-CN/docs/Web/API/GlobalFetch/fetch /zh-CN/docs/Web/API/fetch /zh-CN/docs/Web/API/HTMLAnchorElement/referrer /zh-CN/docs/Web/API/HTMLAnchorElement/referrerPolicy /zh-CN/docs/Web/API/HTMLCanvasElement/捕获流 /zh-CN/docs/Web/API/HTMLCanvasElement/captureStream /zh-CN/docs/Web/API/HTMLElement.click /zh-CN/docs/Web/API/HTMLElement/click @@ -1500,11 +1500,11 @@ /zh-CN/docs/Web/API/Web_Audio_API/最佳实践 /zh-CN/docs/Web/API/Web_Audio_API/Best_practices /zh-CN/docs/Web/API/Window.alert /zh-CN/docs/Web/API/Window/alert /zh-CN/docs/Web/API/Window.applicationCache /zh-CN/docs/Web/API/Window/applicationCache -/zh-CN/docs/Web/API/Window.atob /zh-CN/docs/Web/API/WindowOrWorkerGlobalScope/atob -/zh-CN/docs/Web/API/Window.btoa /zh-CN/docs/Web/API/WindowOrWorkerGlobalScope/btoa +/zh-CN/docs/Web/API/Window.atob /zh-CN/docs/Web/API/atob +/zh-CN/docs/Web/API/Window.btoa /zh-CN/docs/Web/API/btoa /zh-CN/docs/Web/API/Window.cancelAnimationFrame /zh-CN/docs/Web/API/Window/cancelAnimationFrame /zh-CN/docs/Web/API/Window.clearImmediate /zh-CN/docs/Web/API/Window/clearImmediate -/zh-CN/docs/Web/API/Window.clearInterval /zh-CN/docs/Web/API/WindowOrWorkerGlobalScope/clearInterval +/zh-CN/docs/Web/API/Window.clearInterval /zh-CN/docs/Web/API/clearInterval /zh-CN/docs/Web/API/Window.close /zh-CN/docs/Web/API/Window/close /zh-CN/docs/Web/API/Window.document /zh-CN/docs/Web/API/Window/document /zh-CN/docs/Web/API/Window.find /zh-CN/docs/Web/API/Window/find @@ -1545,27 +1545,41 @@ /zh-CN/docs/Web/API/Window.scrollY /zh-CN/docs/Web/API/Window/scrollY /zh-CN/docs/Web/API/Window.self /zh-CN/docs/Web/API/Window/self /zh-CN/docs/Web/API/Window.setImmediate /zh-CN/docs/Web/API/Window/setImmediate -/zh-CN/docs/Web/API/Window.setInterval /zh-CN/docs/Web/API/WindowOrWorkerGlobalScope/setInterval +/zh-CN/docs/Web/API/Window.setInterval /zh-CN/docs/Web/API/setInterval /zh-CN/docs/Web/API/Window.showModalDialog /zh-CN/docs/Web/API/Window/showModalDialog /zh-CN/docs/Web/API/Window.top /zh-CN/docs/Web/API/Window/top /zh-CN/docs/Web/API/Window/Window.blur() /zh-CN/docs/Web/API/Window/blur -/zh-CN/docs/Web/API/Window/atob /zh-CN/docs/Web/API/WindowOrWorkerGlobalScope/atob -/zh-CN/docs/Web/API/Window/btoa /zh-CN/docs/Web/API/WindowOrWorkerGlobalScope/btoa -/zh-CN/docs/Web/API/Window/caches /zh-CN/docs/Web/API/WindowOrWorkerGlobalScope/caches -/zh-CN/docs/Web/API/Window/clearInterval /zh-CN/docs/Web/API/WindowOrWorkerGlobalScope/clearInterval +/zh-CN/docs/Web/API/Window/atob /zh-CN/docs/Web/API/atob +/zh-CN/docs/Web/API/Window/btoa /zh-CN/docs/Web/API/btoa +/zh-CN/docs/Web/API/Window/caches /zh-CN/docs/Web/API/caches +/zh-CN/docs/Web/API/Window/clearInterval /zh-CN/docs/Web/API/clearInterval /zh-CN/docs/Web/API/Window/onbeforeunload /zh-CN/docs/Web/API/WindowEventHandlers/onbeforeunload /zh-CN/docs/Web/API/Window/onhashchange /zh-CN/docs/Web/API/WindowEventHandlers/onhashchange /zh-CN/docs/Web/API/Window/onpopstate /zh-CN/docs/Web/API/WindowEventHandlers/onpopstate /zh-CN/docs/Web/API/Window/onresize /zh-CN/docs/Web/API/GlobalEventHandlers/onresize /zh-CN/docs/Web/API/Window/onunload /zh-CN/docs/Web/API/WindowEventHandlers/onunload -/zh-CN/docs/Web/API/Window/setInterval /zh-CN/docs/Web/API/WindowOrWorkerGlobalScope/setInterval -/zh-CN/docs/Web/API/Window/setTimeout /zh-CN/docs/Web/API/WindowOrWorkerGlobalScope/setTimeout +/zh-CN/docs/Web/API/Window/setInterval /zh-CN/docs/Web/API/setInterval +/zh-CN/docs/Web/API/Window/setTimeout /zh-CN/docs/Web/API/setTimeout /zh-CN/docs/Web/API/WindowBase64 /zh-CN/docs/Web/API/WindowOrWorkerGlobalScope#方法 /zh-CN/docs/Web/API/WindowBase64/Base64_encoding_and_decoding /zh-CN/docs/Glossary/Base64 -/zh-CN/docs/Web/API/WindowBase64/atob /zh-CN/docs/Web/API/WindowOrWorkerGlobalScope/atob -/zh-CN/docs/Web/API/WindowBase64/btoa /zh-CN/docs/Web/API/WindowOrWorkerGlobalScope/btoa +/zh-CN/docs/Web/API/WindowBase64/atob /zh-CN/docs/Web/API/atob +/zh-CN/docs/Web/API/WindowBase64/btoa /zh-CN/docs/Web/API/btoa +/zh-CN/docs/Web/API/WindowOrWorkerGlobalScope/atob /zh-CN/docs/Web/API/atob +/zh-CN/docs/Web/API/WindowOrWorkerGlobalScope/btoa /zh-CN/docs/Web/API/btoa +/zh-CN/docs/Web/API/WindowOrWorkerGlobalScope/caches /zh-CN/docs/Web/API/caches +/zh-CN/docs/Web/API/WindowOrWorkerGlobalScope/clearInterval /zh-CN/docs/Web/API/clearInterval +/zh-CN/docs/Web/API/WindowOrWorkerGlobalScope/clearTimeout /zh-CN/docs/Web/API/clearTimeout +/zh-CN/docs/Web/API/WindowOrWorkerGlobalScope/createImageBitmap /zh-CN/docs/Web/API/createImageBitmap +/zh-CN/docs/Web/API/WindowOrWorkerGlobalScope/crossOriginIsolated /zh-CN/docs/Web/API/crossOriginIsolated +/zh-CN/docs/Web/API/WindowOrWorkerGlobalScope/fetch /zh-CN/docs/Web/API/fetch +/zh-CN/docs/Web/API/WindowOrWorkerGlobalScope/indexedDB /zh-CN/docs/Web/API/indexedDB +/zh-CN/docs/Web/API/WindowOrWorkerGlobalScope/isSecureContext /zh-CN/docs/Web/API/isSecureContext +/zh-CN/docs/Web/API/WindowOrWorkerGlobalScope/origin /zh-CN/docs/Web/API/origin +/zh-CN/docs/Web/API/WindowOrWorkerGlobalScope/queueMicrotask /zh-CN/docs/Web/API/queueMicrotask +/zh-CN/docs/Web/API/WindowOrWorkerGlobalScope/setInterval /zh-CN/docs/Web/API/setInterval +/zh-CN/docs/Web/API/WindowOrWorkerGlobalScope/setTimeout /zh-CN/docs/Web/API/setTimeout /zh-CN/docs/Web/API/WindowTimers /zh-CN/docs/Web/API/WindowOrWorkerGlobalScope -/zh-CN/docs/Web/API/WindowTimers/clearTimeout /zh-CN/docs/Web/API/WindowOrWorkerGlobalScope/clearTimeout +/zh-CN/docs/Web/API/WindowTimers/clearTimeout /zh-CN/docs/Web/API/clearTimeout /zh-CN/docs/Web/API/XMLDocument.load /zh-CN/docs/Web/API/XMLDocument/load /zh-CN/docs/Web/API/XMLHttpRequest/FormData /zh-CN/docs/Web/API/FormData /zh-CN/docs/Web/API/console.dir /zh-CN/docs/Web/API/Console/dir diff --git a/files/zh-cn/_wikihistory.json b/files/zh-cn/_wikihistory.json index fe36d86467..f4f8937676 100644 --- a/files/zh-cn/_wikihistory.json +++ b/files/zh-cn/_wikihistory.json @@ -23987,174 +23987,6 @@ "chrisdavidmills" ] }, - "Web/API/WindowOrWorkerGlobalScope/atob": { - "modified": "2020-10-15T21:07:00.713Z", - "contributors": [ - "RainSlide", - "zhangchen", - "nkliyc", - "dingyanhe", - "xgqfrms-GitHub", - "ziyunfei", - "happyWang", - "teoli", - "khalid32" - ] - }, - "Web/API/WindowOrWorkerGlobalScope/btoa": { - "modified": "2020-10-15T21:06:58.236Z", - "contributors": [ - "RainSlide", - "zhangchen", - "RoXoM", - "Carrotzpc", - "dingyanhe", - "xgqfrms-GitHub", - "ziyunfei", - "teoli", - "khalid32", - "cuixiping" - ] - }, - "Web/API/WindowOrWorkerGlobalScope/caches": { - "modified": "2019-09-21T03:33:16.440Z", - "contributors": [ - "JarvanMo" - ] - }, - "Web/API/WindowOrWorkerGlobalScope/clearInterval": { - "modified": "2020-10-15T21:21:33.193Z", - "contributors": [ - "RainCruise", - "RainSlide", - "luojia", - "teoli", - "khalid32", - "ziyunfei" - ] - }, - "Web/API/WindowOrWorkerGlobalScope/clearTimeout": { - "modified": "2020-06-09T04:49:33.480Z", - "contributors": [ - "Humilitas", - "zhangchen", - "luojia", - "paddingme" - ] - }, - "Web/API/WindowOrWorkerGlobalScope/createImageBitmap": { - "modified": "2019-03-18T20:44:01.174Z", - "contributors": [ - "fanerge", - "varcat" - ] - }, - "Web/API/WindowOrWorkerGlobalScope/crossOriginIsolated": { - "modified": "2020-10-15T22:26:03.129Z", - "contributors": [ - "Fulgrim" - ] - }, - "Web/API/WindowOrWorkerGlobalScope/fetch": { - "modified": "2020-10-15T21:38:47.827Z", - "contributors": [ - "hughfenghen", - "jingkaimori", - "c1er", - "ldc-37", - "Rhys_211", - "zhangchen", - "fscholz", - "TiaossuP", - "Yanzengyong", - "wxs77577", - "Ende93", - "xuzhijun", - "ziyunfei", - "camsong", - "fuchao2012" - ] - }, - "Web/API/WindowOrWorkerGlobalScope/indexedDB": { - "modified": "2019-09-21T03:34:03.050Z", - "contributors": [ - "FEhaoxinjie" - ] - }, - "Web/API/WindowOrWorkerGlobalScope/isSecureContext": { - "modified": "2019-09-21T03:37:23.951Z", - "contributors": [ - "Awe" - ] - }, - "Web/API/WindowOrWorkerGlobalScope/origin": { - "modified": "2019-03-23T22:03:28.077Z", - "contributors": [ - "xgqfrms-GitHub" - ] - }, - "Web/API/WindowOrWorkerGlobalScope/queueMicrotask": { - "modified": "2020-10-15T22:23:11.878Z", - "contributors": [ - "RainSlide" - ] - }, - "Web/API/WindowOrWorkerGlobalScope/setInterval": { - "modified": "2020-11-25T18:16:55.949Z", - "contributors": [ - "RayTang-hub", - "cellinlab", - "Jiangmenghao", - "TXYjing", - "Soul", - "fengbin", - "RainSlide", - "brandonhyc", - "xgqfrms-GitHub", - "shery", - "xgqfrms", - "teoli", - "khalid32", - "ziyunfei", - "sonicview" - ] - }, - "Web/API/WindowOrWorkerGlobalScope/setTimeout": { - "modified": "2020-10-15T21:19:52.746Z", - "contributors": [ - "SnowGojira", - "iyow", - "johnao", - "chrisdavidmills", - "csga31971", - "baijingfeng", - "Reci-z", - "horrylala", - "Adashuai5", - "LilyWakana", - "Mars687", - "pinpinye", - "Lby876176278", - "Chancefeng", - "fscholz", - "xiazhe", - "Frorice", - "yhtml5", - "righttoe", - "Toxni", - "piemonSong", - "xgqfrms-GitHub", - "heke2929", - "SnowOnion", - "Chimen", - "hbkdsm", - "paddingme", - "teoli", - "khalid32", - "Meteormatt", - "ziyunfei" - ] - }, "Web/API/Worker": { "modified": "2020-10-15T21:22:11.206Z", "contributors": [ @@ -24686,6 +24518,74 @@ "Sebastianz" ] }, + "Web/API/atob": { + "modified": "2020-10-15T21:07:00.713Z", + "contributors": [ + "RainSlide", + "zhangchen", + "nkliyc", + "dingyanhe", + "xgqfrms-GitHub", + "ziyunfei", + "happyWang", + "teoli", + "khalid32" + ] + }, + "Web/API/btoa": { + "modified": "2020-10-15T21:06:58.236Z", + "contributors": [ + "RainSlide", + "zhangchen", + "RoXoM", + "Carrotzpc", + "dingyanhe", + "xgqfrms-GitHub", + "ziyunfei", + "teoli", + "khalid32", + "cuixiping" + ] + }, + "Web/API/caches": { + "modified": "2019-09-21T03:33:16.440Z", + "contributors": [ + "JarvanMo" + ] + }, + "Web/API/clearInterval": { + "modified": "2020-10-15T21:21:33.193Z", + "contributors": [ + "RainCruise", + "RainSlide", + "luojia", + "teoli", + "khalid32", + "ziyunfei" + ] + }, + "Web/API/clearTimeout": { + "modified": "2020-06-09T04:49:33.480Z", + "contributors": [ + "Humilitas", + "zhangchen", + "luojia", + "paddingme" + ] + }, + "Web/API/createImageBitmap": { + "modified": "2019-03-18T20:44:01.174Z", + "contributors": [ + "fanerge", + "varcat" + ] + }, + "Web/API/crossOriginIsolated": { + "modified": "2020-10-15T22:26:03.129Z", + "contributors": [ + "Fulgrim" + ] + }, "Web/API/element/scrollWidth": { "modified": "2019-12-11T06:18:59.921Z", "contributors": [ @@ -24700,6 +24600,38 @@ "kuugua" ] }, + "Web/API/fetch": { + "modified": "2020-10-15T21:38:47.827Z", + "contributors": [ + "hughfenghen", + "jingkaimori", + "c1er", + "ldc-37", + "Rhys_211", + "zhangchen", + "fscholz", + "TiaossuP", + "Yanzengyong", + "wxs77577", + "Ende93", + "xuzhijun", + "ziyunfei", + "camsong", + "fuchao2012" + ] + }, + "Web/API/indexedDB": { + "modified": "2019-09-21T03:34:03.050Z", + "contributors": [ + "FEhaoxinjie" + ] + }, + "Web/API/isSecureContext": { + "modified": "2019-09-21T03:37:23.951Z", + "contributors": [ + "Awe" + ] + }, "Web/API/notification": { "modified": "2020-09-28T00:03:47.900Z", "contributors": [ @@ -24823,6 +24755,74 @@ "BSPR0002" ] }, + "Web/API/origin": { + "modified": "2019-03-23T22:03:28.077Z", + "contributors": [ + "xgqfrms-GitHub" + ] + }, + "Web/API/queueMicrotask": { + "modified": "2020-10-15T22:23:11.878Z", + "contributors": [ + "RainSlide" + ] + }, + "Web/API/setInterval": { + "modified": "2020-11-25T18:16:55.949Z", + "contributors": [ + "RayTang-hub", + "cellinlab", + "Jiangmenghao", + "TXYjing", + "Soul", + "fengbin", + "RainSlide", + "brandonhyc", + "xgqfrms-GitHub", + "shery", + "xgqfrms", + "teoli", + "khalid32", + "ziyunfei", + "sonicview" + ] + }, + "Web/API/setTimeout": { + "modified": "2020-10-15T21:19:52.746Z", + "contributors": [ + "SnowGojira", + "iyow", + "johnao", + "chrisdavidmills", + "csga31971", + "baijingfeng", + "Reci-z", + "horrylala", + "Adashuai5", + "LilyWakana", + "Mars687", + "pinpinye", + "Lby876176278", + "Chancefeng", + "fscholz", + "xiazhe", + "Frorice", + "yhtml5", + "righttoe", + "Toxni", + "piemonSong", + "xgqfrms-GitHub", + "heke2929", + "SnowOnion", + "Chimen", + "hbkdsm", + "paddingme", + "teoli", + "khalid32", + "Meteormatt", + "ziyunfei" + ] + }, "Web/Accessibility": { "modified": "2020-08-04T10:11:09.882Z", "contributors": [ diff --git a/files/zh-cn/web/api/atob/index.html b/files/zh-cn/web/api/atob/index.html new file mode 100644 index 0000000000..4679dec8c5 --- /dev/null +++ b/files/zh-cn/web/api/atob/index.html @@ -0,0 +1,75 @@ +--- +title: WindowOrWorkerGlobalScope.atob() +slug: Web/API/atob +tags: + - API + - Base64 + - DOM + - WindowOrWorkerGlobalScope + - atob + - 参考 + - 方法 +translation_of: Web/API/WindowOrWorkerGlobalScope/atob +original_slug: Web/API/WindowOrWorkerGlobalScope/atob +--- +

{{APIRef("HTML DOM")}}

+ +

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

+ +

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

+ +

语法

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

异常

+ +

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

+ +

示例

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

规范

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

浏览器兼容性

+ +

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

+ +

参见

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

{{APIRef("HTML DOM")}}

+ +

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

+ +
+

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

+
+ +

语法

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

参数

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

返回值

+ +

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

+ +

示例

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

备注

+ +

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

+ +

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

+ +

Unicode 字符串

+ +

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

+ +

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

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

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

+ +

规范

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

Polyfill

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

浏览器兼容性

+ +

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

+ +

参见

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

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

+ +

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

+ +

语法

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

+ +

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

+ +

例子

+ +

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

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

规范

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

Browser compatibility

+ +

{{CompatibilityTable}}

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

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

+ +

相关链接

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

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

+ +

语法

+ +
scope.clearInterval(intervalID)
+
+ +

Parameters

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

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

+ +

返回值

+ +

{{jsxref("undefined")}}

+ +

示例

+ +

查看 setInterval() 的示例

+ +

规范

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

浏览器兼容性

+ + + +

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

+ +

参见

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

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

+ +

语法

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

Parameters

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

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

+ +

示例

+ +

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

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

注意

+ +

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

+ +

规范

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

浏览器兼容

+ +

{{CompatibilityTable}}

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

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

+ +

更多

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

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

+ +

Syntax

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

Parameters

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

Return value

+ +

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

+ +

Example

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

Specifications

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

Browser compatibility

+ +

{{ CompatibilityTable}}

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

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

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

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

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

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

+ +

See also

+ +
    +
  • {{domxref("CanvasRenderingContext2D.drawImage()")}}
  • +
  • {{domxref("ImageData")}}
  • +
+ +

+ +

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

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

+ +

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

+ +

语法

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

类型

+ +

布尔类型

+ +

示例

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

规范

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

浏览器兼容性

+ + + +

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

+ +

参见

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

{{APIRef("Fetch")}}

+ +

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

+ +

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

+ +

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

+ +

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

+ +
+

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

+
+ +

语法

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

参数

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

返回值

+ +

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

+ +

例外

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

示例

+ +

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

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

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

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

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

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

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

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

规范

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

浏览器兼容性

+ + + +

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

+ +

相关链接

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

{{ APIRef() }}

+ +

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

+ +

语法

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

+
+ +

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

+ +

示例

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

规范

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

浏览器兼容性

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

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

+ +

相关链接

+ +
    +
  • Using IndexedDB
  • +
  • Starting transactions: {{domxref("IDBDatabase")}}
  • +
  • Using transactions: {{domxref("IDBTransaction")}}
  • +
  • Setting a range of keys: {{domxref("IDBKeyRange")}}
  • +
  • Retrieving and making changes to your data: {{domxref("IDBObjectStore")}}
  • +
  • Using cursors: {{domxref("IDBCursor")}}
  • +
  • Reference example: To-do Notifications (view example live.)
  • +
diff --git a/files/zh-cn/web/api/issecurecontext/index.html b/files/zh-cn/web/api/issecurecontext/index.html new file mode 100644 index 0000000000..355b4dcde6 --- /dev/null +++ b/files/zh-cn/web/api/issecurecontext/index.html @@ -0,0 +1,101 @@ +--- +title: WindowOrWorkerGlobalScope.isSecureContext +slug: Web/API/isSecureContext +tags: + - API + - Property + - Reference + - Window + - WindowOrWorkerGlobalContext + - Workers + - isSecureContext +translation_of: Web/API/WindowOrWorkerGlobalScope/isSecureContext +original_slug: Web/API/WindowOrWorkerGlobalScope/isSecureContext +--- +

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

+ +

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

+ +

语法

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

类型

+ +

 {{domxref("Boolean")}}.

+ +

规范

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

浏览器兼容性

+ +

{{CompatibilityTable}}

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

参考

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

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

+ +

Syntax

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

Value

+ +

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

+ +

Examples

+ +

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

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

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

+ +

Specifications

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

Browser compatibility

+ +

{{CompatibilityTable}}

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

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

+ +

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

+ +

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

+ +

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

+ +

语法

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

参数

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

返回值

+ +

undefined

+ +

示例

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

来自 queueMicrotask 的规范文档:

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

polyfill

+ +

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

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

规范

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

浏览器兼容性

+ +

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

+ +

参见

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

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

+ +

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

+ +

语法

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

参数

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

返回值

+ +

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

+ +

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

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

示例

+ +

例1:基本用法

+ +

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

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

例2:两种颜色的切换

+ +

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

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

例3:打字机效果

+ +

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

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

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

+ +

回调参数

+ +

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

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

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

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

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

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

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

+ +

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

+ +

"this" 的问题

+ +

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

+ +

解释

+ +

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

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

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

+ +

一个可能的解决方案

+ +

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

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

New feature test:

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

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

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

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

+ +

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

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

minidaemon.js

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

语法

+ +

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

+ +

说明

+ +

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

+ +

参数

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

MiniDaemon 实例(instance)的属性

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

MiniDaemon 实例的方法

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

MiniDaemon 全局对象的方法

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

使用示例

+ +

HTML:

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

View this example in action

+ +

备注

+ +

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

+ +

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

+ +

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

+ +

Ensure that execution duration is shorter than interval frequency

+ +

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

+ +

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

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

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

+ +

Throttling of intervals

+ +

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

+ +

规范

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

浏览器兼容性

+ +
+ + +

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

+
+ +

参见

+ +
    +
  • JavaScript 定时器
  • +
  • {{domxref("WindowOrWorkerGlobalScope.setTimeout")}}
  • +
  • {{domxref("WindowOrWorkerGlobalScope.clearTimeout")}}
  • +
  • {{domxref("WindowOrWorkerGlobalScope.clearInterval")}}
  • +
  • {{domxref("window.requestAnimationFrame")}}
  • +
  • Daemons management
  • +
diff --git a/files/zh-cn/web/api/settimeout/index.html b/files/zh-cn/web/api/settimeout/index.html new file mode 100644 index 0000000000..1499eccade --- /dev/null +++ b/files/zh-cn/web/api/settimeout/index.html @@ -0,0 +1,477 @@ +--- +title: window.setTimeout +slug: Web/API/setTimeout +tags: + - Timers + - WindowOrWorkerGlobalScope + - WindowTimers + - setTimeout +translation_of: Web/API/WindowOrWorkerGlobalScope/setTimeout +original_slug: Web/API/WindowOrWorkerGlobalScope/setTimeout +--- +

{{APIRef("HTML DOM")}}

+ +

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

+ +

语法

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

参数

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

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

+
+ +

返回值

+ +

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

+ +

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

+ +

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

+ +

例子

+ +

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

+ +

HTML

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

JavaScript

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

结果展示

+ +

{{EmbedLiveSample('例子')}}

+ +

也可参考 clearTimeout() 示例.

+ +

兼容旧环境(polyfill)

+ +

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

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

针对IE的解决方法

+ +

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

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

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

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

变通方法

+ +

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

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

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

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

此外,也可使用 function's bind

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

关于"this"的问题

+ +

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

+ +

解释

+ +

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

+ +
+

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

+
+ +

查看下面的例子:

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

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

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

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

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

可能的解决方案

+ +

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

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

箭头函数也可以:

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

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

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

新特性检测:

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

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

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

使用bind()的例子:

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

备注

+ +

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

+ +

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

+ +

传递字符串字面量

+ +

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

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

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

+ +

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

+ +

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

+ +

最小延时 >=4ms

+ +

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

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

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

+ +

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

+ +

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

+ +
+

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

+
+ +
+

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

+
+ +

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

+ +

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

+ +

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

+ +

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

+ +
+

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

+
+ +

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

+ +

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

+ +

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

+ +
    +
  • dom.min_tracking_timeout_value: 4
  • +
  • dom.min_tracking_background_timeout_value: 10000
  • +
  • dom.timeout.tracking_throttling_delay: 30000
  • +
+ +

超时延迟

+ +

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

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

会在控制台输出:

+ +
After setTimeout
+foo has been called
+ +

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

+ +

WebExtension Background pages和定时器

+ +

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

+ +

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

+ +

1.兼容Chorme。

+ +

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

+ +

最大延时值

+ +

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

+ +

规范

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

浏览器兼容性

+ +
+ + +

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

+
+ +

相关链接:

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

{{APIRef("HTML DOM")}}

- -

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

- -

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

- -

语法

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

异常

- -

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

- -

示例

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

规范

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

浏览器兼容性

- -

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

- -

参见

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

{{APIRef("HTML DOM")}}

- -

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

- -
-

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

-
- -

语法

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

参数

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

返回值

- -

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

- -

示例

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

备注

- -

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

- -

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

- -

Unicode 字符串

- -

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

- -

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

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

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

- -

规范

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

Polyfill

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

浏览器兼容性

- -

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

- -

参见

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

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

- -

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

- -

语法

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

- -

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

- -

例子

- -

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

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

规范

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

Browser compatibility

- -

{{CompatibilityTable}}

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

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

- -

相关链接

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

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

- -

语法

- -
scope.clearInterval(intervalID)
-
- -

Parameters

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

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

- -

返回值

- -

{{jsxref("undefined")}}

- -

示例

- -

查看 setInterval() 的示例

- -

规范

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

浏览器兼容性

- - - -

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

- -

参见

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

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

- -

语法

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

Parameters

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

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

- -

示例

- -

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

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

注意

- -

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

- -

规范

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

浏览器兼容

- -

{{CompatibilityTable}}

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

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

- -

更多

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

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

- -

Syntax

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

Parameters

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

Return value

- -

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

- -

Example

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

Specifications

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

Browser compatibility

- -

{{ CompatibilityTable}}

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

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

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

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

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

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

- -

See also

- -
    -
  • {{domxref("CanvasRenderingContext2D.drawImage()")}}
  • -
  • {{domxref("ImageData")}}
  • -
- -

- -

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

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

- -

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

- -

语法

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

类型

- -

布尔类型

- -

示例

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

规范

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

浏览器兼容性

- - - -

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

- -

参见

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

{{APIRef("Fetch")}}

- -

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

- -

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

- -

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

- -

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

- -
-

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

-
- -

语法

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

参数

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

返回值

- -

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

- -

例外

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

示例

- -

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

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

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

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

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

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

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

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

规范

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

浏览器兼容性

- - - -

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

- -

相关链接

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

{{ APIRef() }}

- -

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

- -

语法

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

-
- -

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

- -

示例

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

规范

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

浏览器兼容性

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

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

- -

相关链接

- -
    -
  • Using IndexedDB
  • -
  • Starting transactions: {{domxref("IDBDatabase")}}
  • -
  • Using transactions: {{domxref("IDBTransaction")}}
  • -
  • Setting a range of keys: {{domxref("IDBKeyRange")}}
  • -
  • Retrieving and making changes to your data: {{domxref("IDBObjectStore")}}
  • -
  • Using cursors: {{domxref("IDBCursor")}}
  • -
  • Reference example: To-do Notifications (view example live.)
  • -
diff --git a/files/zh-cn/web/api/windoworworkerglobalscope/issecurecontext/index.html b/files/zh-cn/web/api/windoworworkerglobalscope/issecurecontext/index.html deleted file mode 100644 index d9f72b13a5..0000000000 --- a/files/zh-cn/web/api/windoworworkerglobalscope/issecurecontext/index.html +++ /dev/null @@ -1,100 +0,0 @@ ---- -title: WindowOrWorkerGlobalScope.isSecureContext -slug: Web/API/WindowOrWorkerGlobalScope/isSecureContext -tags: - - API - - Property - - Reference - - Window - - WindowOrWorkerGlobalContext - - Workers - - isSecureContext -translation_of: Web/API/WindowOrWorkerGlobalScope/isSecureContext ---- -

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

- -

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

- -

语法

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

类型

- -

 {{domxref("Boolean")}}.

- -

规范

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

浏览器兼容性

- -

{{CompatibilityTable}}

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

参考

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

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

- -

Syntax

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

Value

- -

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

- -

Examples

- -

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

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

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

- -

Specifications

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

Browser compatibility

- -

{{CompatibilityTable}}

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

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

- -

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

- -

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

- -

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

- -

语法

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

参数

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

返回值

- -

undefined

- -

示例

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

来自 queueMicrotask 的规范文档:

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

polyfill

- -

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

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

规范

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

浏览器兼容性

- -

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

- -

参见

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

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

- -

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

- -

语法

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

参数

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

返回值

- -

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

- -

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

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

示例

- -

例1:基本用法

- -

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

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

例2:两种颜色的切换

- -

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

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

例3:打字机效果

- -

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

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

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

- -

回调参数

- -

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

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

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

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

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

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

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

- -

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

- -

"this" 的问题

- -

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

- -

解释

- -

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

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

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

- -

一个可能的解决方案

- -

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

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

New feature test:

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

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

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

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

- -

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

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

minidaemon.js

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

语法

- -

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

- -

说明

- -

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

- -

参数

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

MiniDaemon 实例(instance)的属性

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

MiniDaemon 实例的方法

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

MiniDaemon 全局对象的方法

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

使用示例

- -

HTML:

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

View this example in action

- -

备注

- -

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

- -

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

- -

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

- -

Ensure that execution duration is shorter than interval frequency

- -

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

- -

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

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

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

- -

Throttling of intervals

- -

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

- -

规范

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

浏览器兼容性

- -
- - -

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

-
- -

参见

- -
    -
  • JavaScript 定时器
  • -
  • {{domxref("WindowOrWorkerGlobalScope.setTimeout")}}
  • -
  • {{domxref("WindowOrWorkerGlobalScope.clearTimeout")}}
  • -
  • {{domxref("WindowOrWorkerGlobalScope.clearInterval")}}
  • -
  • {{domxref("window.requestAnimationFrame")}}
  • -
  • Daemons management
  • -
diff --git a/files/zh-cn/web/api/windoworworkerglobalscope/settimeout/index.html b/files/zh-cn/web/api/windoworworkerglobalscope/settimeout/index.html deleted file mode 100644 index d0c80bb95b..0000000000 --- a/files/zh-cn/web/api/windoworworkerglobalscope/settimeout/index.html +++ /dev/null @@ -1,477 +0,0 @@ ---- -title: window.setTimeout -slug: Web/API/WindowOrWorkerGlobalScope/setTimeout -tags: - - Timers - - WindowOrWorkerGlobalScope - - WindowTimers - - setTimeout -translation_of: Web/API/WindowOrWorkerGlobalScope/setTimeout -original_slug: Web/API/Window/setTimeout ---- -

{{APIRef("HTML DOM")}}

- -

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

- -

语法

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

参数

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

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

-
- -

返回值

- -

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

- -

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

- -

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

- -

例子

- -

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

- -

HTML

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

JavaScript

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

结果展示

- -

{{EmbedLiveSample('例子')}}

- -

也可参考 clearTimeout() 示例.

- -

兼容旧环境(polyfill)

- -

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

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

针对IE的解决方法

- -

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

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

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

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

变通方法

- -

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

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

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

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

此外,也可使用 function's bind

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

关于"this"的问题

- -

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

- -

解释

- -

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

- -
-

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

-
- -

查看下面的例子:

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

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

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

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

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

可能的解决方案

- -

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

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

箭头函数也可以:

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

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

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

新特性检测:

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

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

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

使用bind()的例子:

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

备注

- -

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

- -

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

- -

传递字符串字面量

- -

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

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

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

- -

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

- -

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

- -

最小延时 >=4ms

- -

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

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

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

- -

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

- -

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

- -
-

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

-
- -
-

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

-
- -

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

- -

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

- -

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

- -

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

- -
-

当 Web Audio API {{domxref("AudioContext")}} 正在被用来播放音频的时候,Firefox 50不会再限制后台tabs的加载。 后续的Firefox 51 版本修正了这个问题,即使在没有音频播放的情况下,也不再限制后台tabs的加载。这个解决了一些软件应用在后台tabs中播放基于文本的音频( note-based) 时,无法去同步音频和画面的问题。

-
- -

追踪型脚本的最小延时限制

- -

从Firefox 55版本开始,追踪型脚本(例如 谷歌分析,或者其他的一些被Firefox 的 TP lists 识别为追踪型脚本的 外链URL脚本)是重点限制加载的对象。在当前正在使用的页面中,这个节流限制的延时依然是4ms。但是在后台tabs中,这个最小延时限制是10000ms(10s),这个限制会在文档第一次加载后的30s后生效。

- -

控制这些行为的属性包含以下这些:

- -
    -
  • dom.min_tracking_timeout_value: 4
  • -
  • dom.min_tracking_background_timeout_value: 10000
  • -
  • dom.timeout.tracking_throttling_delay: 30000
  • -
- -

超时延迟

- -

除了"最小延时"之外,定时器仍然有可能因为当前页面(或者操作系统/浏览器本身)被其他任务占用导致延时。 需要被强调是, 直到调用 setTimeout()的主线程执行完其他任务之后,回调函数和代码段才能被执行。例如:

- -
function foo() {
-  console.log('foo has been called');
-}
-setTimeout(foo, 0);
-console.log('After setTimeout');
- -

会在控制台输出:

- -
After setTimeout
-foo has been called
- -

出现这个结果的原因是,尽管setTimeout 以0ms的延迟来调用函数,但这个任务已经被放入了队列中并且等待下一次执行;并不是立即执行;队列中的等待函数被调用之前,当前代码必须全部运行完毕,因此这里运行结果并非预想的那样。

- -

WebExtension Background pages和定时器

- -

在 WebExtension 中 background pages,timers工作不正常。这主要因为background pages实际上,并不是一次性全部加载:如果浏览器没有使用它,就不加载,如果需要就恢复。这对于WebExtension是透明的,但是有些事件(包括JS的timers)不会在不加载/恢复循环中执行,所以WebExtension中建议使用alarms。更详细的细节在合并到事件驱动后台脚本

- -

在本文写作的时候,只有Chrome展示了如上的特性 — Firefox没有未加载/恢复循环的行为,所以timers仍然可以工作。但是,仍然建议不要在WebExtension中使用timers:

- -

1.兼容Chorme。

- -

2.未来行为的改变会引起问题。

- -

最大延时值

- -

包括 IE,  Chrome, Safari, Firefox 在内的浏览器其内部以32位带符号整数存储延时。这就会导致如果一个延时(delay)大于 2147483647 毫秒 (大约24.8 天)时就会溢出,导致定时器将会被立即执行。

- -

规范

- - - - - - - - - - - - - - - - - - - - - -
SpecificationStatusComment
{{SpecName('HTML WHATWG', 'webappapis.html#dom-settimeout', 'WindowOrWorkerGlobalScope.setTimeout()')}}{{Spec2("HTML WHATWG")}}Method moved to the WindowOrWorkerGlobalScope mixin in the latest spec.
{{SpecName("HTML WHATWG", "webappapis.html#dom-settimeout", "WindowTimers.setTimeout()")}}{{Spec2("HTML WHATWG")}}Initial definition (DOM Level 0)
- -

浏览器兼容性

- -
- - -

{{Compat("api.WindowOrWorkerGlobalScope.setTimeout")}}

-
- -

相关链接:

- - diff --git a/files/zh-tw/_redirects.txt b/files/zh-tw/_redirects.txt index a74261d6e4..079c3da530 100644 --- a/files/zh-tw/_redirects.txt +++ b/files/zh-tw/_redirects.txt @@ -571,6 +571,8 @@ /zh-TW/docs/Web/API/Window.requestAnimationFrame /zh-TW/docs/Web/API/window/requestAnimationFrame /zh-TW/docs/Web/API/Window/sidebar/Adding_search_engines_from_Web_pages /zh-TW/docs/conflicting/Web/OpenSearch /zh-TW/docs/Web/API/WindowBase64 /zh-TW/docs/conflicting/Web/API/WindowOrWorkerGlobalScope +/zh-TW/docs/Web/API/WindowOrWorkerGlobalScope/btoa /zh-TW/docs/Web/API/btoa +/zh-TW/docs/Web/API/WindowOrWorkerGlobalScope/setInterval /zh-TW/docs/Web/API/setInterval /zh-TW/docs/Web/API/WindowTimers /zh-TW/docs/conflicting/Web/API/WindowOrWorkerGlobalScope_e2691f7ad05781a30c5fc5bb3b3f633a /zh-TW/docs/Web/API/XMLHttpRequest/FormData /zh-TW/docs/Web/API/FormData /zh-TW/docs/Web/API/document.createTreeWalker /zh-TW/docs/Web/API/Document/createTreeWalker diff --git a/files/zh-tw/_wikihistory.json b/files/zh-tw/_wikihistory.json index 74a41f5f01..a3732164fe 100644 --- a/files/zh-tw/_wikihistory.json +++ b/files/zh-tw/_wikihistory.json @@ -4722,18 +4722,6 @@ "mfuji09" ] }, - "Web/API/WindowOrWorkerGlobalScope/btoa": { - "modified": "2020-10-15T22:35:15.820Z", - "contributors": [ - "evo938evo938" - ] - }, - "Web/API/WindowOrWorkerGlobalScope/setInterval": { - "modified": "2020-10-15T22:29:07.467Z", - "contributors": [ - "chrischi0922s" - ] - }, "Web/API/XMLHttpRequest": { "modified": "2020-10-15T21:21:13.079Z", "contributors": [ @@ -4806,6 +4794,12 @@ "jackblackevo" ] }, + "Web/API/btoa": { + "modified": "2020-10-15T22:35:15.820Z", + "contributors": [ + "evo938evo938" + ] + }, "Web/API/console/assert": { "modified": "2020-10-15T22:03:27.482Z", "contributors": [ @@ -4822,6 +4816,12 @@ "Shiyou" ] }, + "Web/API/setInterval": { + "modified": "2020-10-15T22:29:07.467Z", + "contributors": [ + "chrischi0922s" + ] + }, "Web/API/window/requestAnimationFrame": { "modified": "2020-10-15T21:24:54.235Z", "contributors": [ diff --git a/files/zh-tw/web/api/btoa/index.html b/files/zh-tw/web/api/btoa/index.html new file mode 100644 index 0000000000..9f846d885d --- /dev/null +++ b/files/zh-tw/web/api/btoa/index.html @@ -0,0 +1,137 @@ +--- +title: WindowOrWorkerGlobalScope.btoa() +slug: Web/API/btoa +translation_of: Web/API/WindowOrWorkerGlobalScope/btoa +original_slug: Web/API/WindowOrWorkerGlobalScope/btoa +--- +

{{APIRef("HTML DOM")}}

+ +

The WindowOrWorkerGlobalScope.btoa() method creates a {{glossary("Base64")}}-encoded ASCII string from a binary string (i.e., a {{jsxref("String")}} object in which each character in the string is treated as a byte of binary data).

+ +

You can use this method to encode data which may otherwise cause communication problems, transmit it, then use the {{domxref("WindowOrWorkerGlobalScope.atob", "atob()")}} method to decode the data again. For example, you can encode control characters such as ASCII values 0 through 31.

+ +

Syntax

+ +
var encodedData = scope.btoa(stringToEncode);
+ +

Parameters

+ +
+
stringToEncode
+
The binary string to encode.
+
+ +

Return value

+ +

An ASCII string containing the Base64 representation of stringToEncode.

+ +

Exceptions

+ +
+
InvalidCharacterError
+
The string contained a character that did not fit in a single byte. See "Unicode strings" below for more detail.
+
+ +

Example

+ +
const encodedData = window.btoa('Hello, world'); // encode a string
+const decodedData = window.atob(encodedData); // decode the string
+
+ +

Unicode strings

+ +

The btoa() function takes a JavaScript string as a parameter. In JavaScript strings are represented using the UTF-16 character encoding: in this encoding, strings are represented as a sequence of 16-bit (2 byte) units. Every ASCII character fits into the first byte of one of these units, but many other characters don't.

+ +

Base64, by design, expects binary data as its input. In terms of JavaScript strings, this means strings in which each character occupies only one byte. So if you pass a string into btoa() containing characters that occupy more than one byte, you will get an error, because this is not considered binary data:

+ +
const ok = "a";
+console.log(ok.codePointAt(0).toString(16)); //   61: occupies < 1 byte
+
+const notOK = "✓"
+console.log(notOK.codePointAt(0).toString(16)); // 2713: occupies > 1 byte
+
+console.log(btoa(ok));    // YQ==
+console.log(btoa(notOK)); // error
+ +

If you need to encode Unicode text as ASCII using btoa(), one option is to convert the string such that each 16-bit unit occupies only one byte. For example:

+ +
// convert a Unicode string to a string in which
+// each 16-bit unit occupies only one byte
+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));
+}
+
+// a string that contains characters occupying > 1 byte
+const myString = "☸☹☺☻☼☾☿";
+
+const converted = toBinary(myString);
+const encoded = btoa(converted);
+console.log(encoded);                 // OCY5JjomOyY8Jj4mPyY=
+
+ +

If you do this, of course you'll have to reverse the conversion on the decoded string:

+ +
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);                // ☸☹☺☻☼☾☿
+
+ +

Polyfill

+ +

You can use a polyfill from https://github.com/MaxArt2501/base64-js/blob/master/base64.js for browsers that don't support it.

+ +

Specifications

+ + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('HTML WHATWG', '#dom-btoa', 'WindowOrWorkerGlobalScope.btoa()')}}{{Spec2('HTML WHATWG')}}Method moved to the WindowOrWorkerGlobalScope mixin in the latest spec.
{{SpecName('HTML5.1', '#dom-windowbase64-btoa', 'WindowBase64.btoa()')}}{{Spec2('HTML5.1')}}Snapshot of {{SpecName("HTML WHATWG")}}. No change.
{{SpecName("HTML5 W3C", "#dom-windowbase64-btoa", "WindowBase64.btoa()")}}{{Spec2('HTML5 W3C')}}Snapshot of {{SpecName("HTML WHATWG")}}. Creation of WindowBase64 (properties where on the target before it).
+ +

Browser compatibility

+ +
+ + +

{{Compat("api.WindowOrWorkerGlobalScope.btoa")}}

+
+ +

See also

+ +
    +
  • data URIs
  • +
  • {{domxref("WindowOrWorkerGlobalScope.atob","atob()")}}
  • +
diff --git a/files/zh-tw/web/api/setinterval/index.html b/files/zh-tw/web/api/setinterval/index.html new file mode 100644 index 0000000000..ac8ee376e0 --- /dev/null +++ b/files/zh-tw/web/api/setinterval/index.html @@ -0,0 +1,628 @@ +--- +title: WindowOrWorkerGlobalScope.setInterval() +slug: Web/API/setInterval +translation_of: Web/API/WindowOrWorkerGlobalScope/setInterval +original_slug: Web/API/WindowOrWorkerGlobalScope/setInterval +--- +
{{APIRef("HTML DOM")}}
+ +

setInterval() 函式, {{domxref("Window")}} 與 {{domxref("Worker")}} 介面皆提供此一函式, 此函式作用為重複地執行一個函式呼叫或一個程式碼片斷, 每一次執行間隔固定的延遲時間. 此函式呼叫時將傳回一個間隔代碼(Interval ID)用以識別該間隔程序, 因此後續您可以呼叫 {{domxref("WindowOrWorkerGlobalScope.clearInterval", "clearInterval()")}} 函式移除該間隔程序. 此函式為由 {{domxref("WindowOrWorkerGlobalScope")}} 混合定義.

+ +

Syntax

+ +
var intervalID = scope.setInterval(func, [delay, arg1, arg2, ...]);
+var intervalID = scope.setInterval(code, [delay]);
+
+ +

Parameters

+ +
+
func
+
A {{jsxref("function")}} to be executed every delay milliseconds. The function is not passed any arguments, and no return value is expected.
+
code
+
An optional syntax allows you to include a string instead of a function, which is compiled and executed every delay milliseconds. This syntax is not recommended for the same reasons that make using {{jsxref("eval", "eval()")}} a security risk.
+
delay{{optional_inline}}
+
The time, in milliseconds (thousandths of a second), the timer should delay in between executions of the specified function or code. See {{anch("Delay restrictions")}} below for details on the permitted range of delay values.
+
arg1, ..., argN {{optional_inline}}
+
Additional arguments which are passed through to the function specified by func once the timer expires.
+
+ +
+

Note: Passing additional arguments to setInterval() in the first syntax does not work in Internet Explorer 9 and earlier. If you want to enable this functionality on that browser, you must use a polyfill (see the Callback arguments section).

+
+ +

Return value

+ +

The returned intervalID is a numeric, non-zero value which identifies the timer created by the call to setInterval(); this value can be passed to {{domxref("WindowOrWorkerGlobalScope.clearInterval()")}} to cancel the timeout.

+ +

It may be helpful to be aware that setInterval() and {{domxref("WindowOrWorkerGlobalScope.setTimeout", "setTimeout()")}} share the same pool of IDs, and that clearInterval() and {{domxref("WindowOrWorkerGlobalScope.clearTimeout", "clearTimeout()")}} can technically be used interchangeably. For clarity, however, you should try to always match them to avoid confusion when maintaining your code.

+ +
Note: The delay argument is converted to a signed 32-bit integer. This effectively limits delay to 2147483647 ms, since it's specified as a signed integer in the IDL.
+ +

Examples

+ +

Example 1: Basic syntax

+ +

The following example demonstrates setInterval()'s basic syntax.

+ +
var intervalID = window.setInterval(myCallback, 500, 'Parameter 1', 'Parameter 2');
+
+function myCallback(a, b)
+{
+ // Your code here
+ // Parameters are purely optional.
+ console.log(a);
+ console.log(b);
+}
+
+ +

Example 2: Alternating two colors

+ +

The following example calls the flashtext() function once a second until the Stop button is pressed.

+ +
<!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>
+
+ +

Example 3: Typewriter simulation

+ +

The following example simulates typewriter by first clearing and then slowly typing content into the NodeList that matches a specified group of selectors.

+ +
<!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().

+ +

Callback arguments

+ +

As previously discussed, Internet Explorer versions 9 and below do not support the passing of arguments to the callback function in either setTimeout() or setInterval(). The following IE-specific code demonstrates a method for overcoming this limitation.  To use, simply add the following code to the top of your script.

+ +
/*\
+|*|
+|*|  IE-specific polyfill that enables the passage of arbitrary arguments to the
+|*|  callback functions of javascript timers (HTML5 standard syntax).
+|*|
+|*|  https://developer.mozilla.org/en-US/docs/Web/API/window.setInterval
+|*|  https://developer.mozilla.org/User:fusionchess
+|*|
+|*|  Syntax:
+|*|  var timeoutID = window.setTimeout(func, delay[, arg1, arg2, ...]);
+|*|  var timeoutID = window.setTimeout(code, delay);
+|*|  var intervalID = window.setInterval(func, delay[, arg1, arg2, ...]);
+|*|  var intervalID = window.setInterval(code, delay);
+|*|
+\*/
+
+if (document.all && !window.setTimeout.isPolyfill) {
+  var __nativeST__ = window.setTimeout;
+  window.setTimeout = function (vCallback, nDelay /*, argumentToPass1, argumentToPass2, etc. */) {
+    var aArgs = Array.prototype.slice.call(arguments, 2);
+    return __nativeST__(vCallback instanceof Function ? function () {
+      vCallback.apply(null, aArgs);
+    } : vCallback, nDelay);
+  };
+  window.setTimeout.isPolyfill = true;
+}
+
+if (document.all && !window.setInterval.isPolyfill) {
+  var __nativeSI__ = window.setInterval;
+  window.setInterval = function (vCallback, nDelay /*, argumentToPass1, argumentToPass2, etc. */) {
+    var aArgs = Array.prototype.slice.call(arguments, 2);
+    return __nativeSI__(vCallback instanceof Function ? function () {
+      vCallback.apply(null, aArgs);
+    } : vCallback, nDelay);
+  };
+  window.setInterval.isPolyfill = true;
+}
+
+ +

Another possibility is to use an anonymous function to call your callback, although this solution is a bit more expensive. Example:

+ +
var intervalID = setInterval(function() { myFunc('one', 'two', 'three'); }, 1000);
+ +

Another possibility is to use function's bind. Example:

+ +
var intervalID = setInterval(function(arg1) {}.bind(undefined, 10), 1000);
+ +

{{h3_gecko_minversion("Inactive tabs", "5.0")}}

+ +

Starting in Gecko 5.0 {{geckoRelease("5.0")}}, intervals are clamped to fire no more often than once per second in inactive tabs.

+ +

The "this" problem

+ +

When you pass a method to setInterval() or any other function, it is invoked with the wrong this value. This problem is explained in detail in the JavaScript reference.

+ +

Explanation

+ +

Code executed by setInterval() runs in a separate execution context than the function from which it was called. As a consequence, the this keyword for the called function is set to the window (or global) object, it is not the same as the this value for the function that called setTimeout. See the following example (which uses setTimeout() instead of setInterval() – the problem, in fact, is the same for both timers):

+ +
myArray = ['zero', 'one', 'two'];
+
+myArray.myMethod = function (sProperty) {
+    alert(arguments.length > 0 ? this[sProperty] : this);
+};
+
+myArray.myMethod(); // prints "zero,one,two"
+myArray.myMethod(1); // prints "one"
+setTimeout(myArray.myMethod, 1000); // prints "[object Window]" after 1 second
+setTimeout(myArray.myMethod, 1500, "1"); // prints "undefined" after 1,5 seconds
+// passing the 'this' object with .call won't work
+// because this will change the value of this inside setTimeout itself
+// while we want to change the value of this inside myArray.myMethod
+// in fact, it will be an error because setTimeout code expects this to be the window object:
+setTimeout.call(myArray, myArray.myMethod, 2000); // error: "NS_ERROR_XPC_BAD_OP_ON_WN_PROTO: Illegal operation on WrappedNative prototype object"
+setTimeout.call(myArray, myArray.myMethod, 2500, 2); // same error
+
+ +

As you can see there are no ways to pass the this object to the callback function in the legacy JavaScript.

+ +

A possible solution

+ +

A possible way to solve the "this" problem is to replace the two native setTimeout() or setInterval() global functions with two non-native ones that enable their invocation through the Function.prototype.call method. The following example shows a possible replacement:

+ +
// Enable the passage of the 'this' object through the JavaScript timers
+
+var __nativeST__ = window.setTimeout, __nativeSI__ = window.setInterval;
+
+window.setTimeout = function (vCallback, nDelay /*, argumentToPass1, argumentToPass2, etc. */) {
+  var oThis = this, aArgs = Array.prototype.slice.call(arguments, 2);
+  return __nativeST__(vCallback instanceof Function ? function () {
+    vCallback.apply(oThis, aArgs);
+  } : vCallback, nDelay);
+};
+
+window.setInterval = function (vCallback, nDelay /*, argumentToPass1, argumentToPass2, etc. */) {
+  var oThis = this, aArgs = Array.prototype.slice.call(arguments, 2);
+  return __nativeSI__(vCallback instanceof Function ? function () {
+    vCallback.apply(oThis, aArgs);
+  } : vCallback, nDelay);
+};
+ +
These two replacements also enable the HTML5 standard passage of arbitrary arguments to the callback functions of timers in IE. So they can be used as non-standard-compliant polyfills also. See the callback arguments paragraph for a standard-compliant polyfill.
+ +

New feature test:

+ +
myArray = ['zero', 'one', 'two'];
+
+myArray.myMethod = function (sProperty) {
+    alert(arguments.length > 0 ? this[sProperty] : this);
+};
+
+setTimeout(alert, 1500, 'Hello world!'); // the standard use of setTimeout and setInterval is preserved, but...
+setTimeout.call(myArray, myArray.myMethod, 2000); // prints "zero,one,two" after 2 seconds
+setTimeout.call(myArray, myArray.myMethod, 2500, 2); // prints "two" after 2,5 seconds
+
+ +

Another, more complex, solution for the this problem is the following framework.

+ +
JavaScript 1.8.5 introduces the Function.prototype.bind() method, which lets you specify the value that should be used as this for all calls to a given function. This lets you easily bypass problems where it's unclear what this will be, depending on the context from which your function was called. Also, ES2015 supports arrow functions, with lexical this allowing us to write setInterval( () => this.myMethod) if we're inside myArray method.
+ +

MiniDaemon - A framework for managing timers

+ +

In pages requiring many timers, it can often be difficult to keep track of all of the running timer events. One approach to solving this problem is to store information about the state of a timer in an object. Following is a minimal example of such an abstraction. The constructor architecture explicitly avoids the use of closures. It also offers an alternative way to pass the this object to the callback function (see The "this" problem for details). The following code is also available on GitHub.

+ +
For a more complex but still modular version of it (Daemon) see JavaScript Daemons Management. This more complex version is nothing but a big and scalable collection of methods for the Daemon constructor. However, the Daemon constructor itself is nothing but a clone of MiniDaemon with an added support for init and onstart functions declarable during the instantiation of the daemon. So the MiniDaemon framework remains the recommended way for simple animations, because Daemon without its collection of methods is essentially a clone of it.
+ +

minidaemon.js

+ +
/*\
+|*|
+|*|  :: MiniDaemon ::
+|*|
+|*|  Revision #2 - September 26, 2014
+|*|
+|*|  https://developer.mozilla.org/en-US/docs/Web/API/window.setInterval
+|*|  https://developer.mozilla.org/User:fusionchess
+|*|  https://github.com/madmurphy/minidaemon.js
+|*|
+|*|  This framework is released under the GNU Lesser General Public License, version 3 or later.
+|*|  http://www.gnu.org/licenses/lgpl-3.0.html
+|*|
+\*/
+
+function MiniDaemon (oOwner, fTask, nRate, nLen) {
+  if (!(this && this instanceof MiniDaemon)) { return; }
+  if (arguments.length < 2) { throw new TypeError('MiniDaemon - not enough arguments'); }
+  if (oOwner) { this.owner = oOwner; }
+  this.task = fTask;
+  if (isFinite(nRate) && nRate > 0) { this.rate = Math.floor(nRate); }
+  if (nLen > 0) { this.length = Math.floor(nLen); }
+}
+
+MiniDaemon.prototype.owner = null;
+MiniDaemon.prototype.task = null;
+MiniDaemon.prototype.rate = 100;
+MiniDaemon.prototype.length = Infinity;
+
+  /* These properties should be read-only */
+
+MiniDaemon.prototype.SESSION = -1;
+MiniDaemon.prototype.INDEX = 0;
+MiniDaemon.prototype.PAUSED = true;
+MiniDaemon.prototype.BACKW = true;
+
+  /* Global methods */
+
+MiniDaemon.forceCall = function (oDmn) {
+  oDmn.INDEX += oDmn.BACKW ? -1 : 1;
+  if (oDmn.task.call(oDmn.owner, oDmn.INDEX, oDmn.length, oDmn.BACKW) === false || oDmn.isAtEnd()) { oDmn.pause(); return false; }
+  return true;
+};
+
+  /* Instances methods */
+
+MiniDaemon.prototype.isAtEnd = function () {
+  return this.BACKW ? isFinite(this.length) && this.INDEX < 1 : this.INDEX + 1 > this.length;
+};
+
+MiniDaemon.prototype.synchronize = function () {
+  if (this.PAUSED) { return; }
+  clearInterval(this.SESSION);
+  this.SESSION = setInterval(MiniDaemon.forceCall, this.rate, this);
+};
+
+MiniDaemon.prototype.pause = function () {
+  clearInterval(this.SESSION);
+  this.PAUSED = true;
+};
+
+MiniDaemon.prototype.start = function (bReverse) {
+  var bBackw = Boolean(bReverse);
+  if (this.BACKW === bBackw && (this.isAtEnd() || !this.PAUSED)) { return; }
+  this.BACKW = bBackw;
+  this.PAUSED = false;
+  this.synchronize();
+};
+
+ +
MiniDaemon passes arguments to the callback function. If you want to work on it with browsers that natively do not support this feature, use one of the methods proposed above.
+ +

Syntax

+ +

var myDaemon = new MiniDaemon(thisObject, callback[, rate[, length]]);

+ +

Description

+ +

Returns a JavaScript Object containing all information needed by an animation (like the this object, the callback function, the length, the frame-rate).

+ +

Arguments

+ +
+
thisObject
+
The this object on which the callback function is called. It can be an object or null.
+
callback
+
The function that is repeatedly invoked . It is called with three arguments: index (the iterative index of each invocation), length (the number of total invocations assigned to the daemon - finite or Infinity) and backwards (a boolean expressing whether the index is increasing or decreasing). It is something like callback.call(thisObject, index, length, backwards). If the callback function returns a false value the daemon is paused.
+
rate (optional)
+
The time lapse (in number of milliseconds) between each invocation. The default value is 100.
+
length (optional)
+
The total number of invocations. It can be a positive integer or Infinity. The default value is Infinity.
+
+ +

MiniDaemon instances properties

+ +
+
myDaemon.owner
+
The this object on which is executed the daemon (read/write). It can be an object or null.
+
myDaemon.task
+
The function that is repeatedly invoked (read/write). It is called with three arguments: index (the iterative index of each invocation), length (the number of total invocations assigned to the daemon - finite or Infinity) and backwards (a boolean expressing whether the index is decreasing or not) – see above. If the myDaemon.task function returns a false value the daemon is paused.
+
myDaemon.rate
+
The time lapse (in number of milliseconds) between each invocation (read/write).
+
myDaemon.length
+
The total number of invocations. It can be a positive integer or Infinity (read/write).
+
+ +

MiniDaemon instances methods

+ +
+
myDaemon.isAtEnd()
+
Returns a boolean expressing whether the daemon is at the start/end position or not.
+
myDaemon.synchronize()
+
Synchronize the timer of a started daemon with the time of its invocation.
+
myDaemon.pause()
+
Pauses the daemon.
+
myDaemon.start([reverse])
+
Starts the daemon forward (index of each invocation increasing) or backwards (index decreasing).
+
+ +

MiniDaemon global object methods

+ +
+
MiniDaemon.forceCall(minidaemon)
+
Forces a single callback to the minidaemon.task function regardless of the fact that the end has been reached or not. In any case the internal INDEX property is increased/decreased (depending on the actual direction of the process).
+
+ +

Example usage

+ +

Your HTML page:

+ +
<!DOCTYPE html>
+<html>
+<head>
+  <meta charset="UTF-8" />
+  <title>MiniDaemin Example - MDN</title>
+  <script type="text/javascript" src="minidaemon.js"></script>
+  <style type="text/css">
+    #sample_div {
+      visibility: hidden;
+    }
+  </style>
+</head>
+
+<body>
+  <p>
+    <input type="button" onclick="fadeInOut.start(false /* optional */);" value="fade in" />
+    <input type="button" onclick="fadeInOut.start(true);" value="fade out">
+    <input type="button" onclick="fadeInOut.pause();" value="pause" />
+  </p>
+
+  <div id="sample_div">Some text here</div>
+
+  <script type="text/javascript">
+    function opacity (nIndex, nLength, bBackwards) {
+      this.style.opacity = nIndex / nLength;
+      if (bBackwards ? nIndex === 0 : nIndex === 1) {
+        this.style.visibility = bBackwards ? 'hidden' : 'visible';
+      }
+    }
+
+    var fadeInOut = new MiniDaemon(document.getElementById('sample_div'), opacity, 300, 8);
+  </script>
+</body>
+</html>
+ +

View this example in action

+ +

Usage notes

+ +

The setInterval() function is commonly used to set a delay for functions that are executed again and again, such as animations. You can cancel the interval using {{domxref("WindowOrWorkerGlobalScope.clearInterval()")}}.

+ +

If you wish to have your function called once after the specified delay, use {{domxref("WindowOrWorkerGlobalScope.setTimeout()")}}.

+ +

Delay restrictions

+ +

It's possible for intervals to be nested; that is, the callback for setInterval() can in turn call setInterval() to start another interval running, even though the first one is still going. To mitigate the potential impact this can have on performance, once intervals are nested beyond five levels deep, the browser will automatically enforce a 4 ms minimum value for the interval. Attempts to specify a value less than 4 ms in deeply-nested calls to setInterval() will be pinned to 4 ms.

+ +

Browsers may enforce even more stringent minimum values for the interval under some circumstances, although these should not be common. Note also that the actual amount of time that elapses between calls to the callback may be longer than the given delay; see {{SectionOnPage("/en-US/docs/Web/API/WindowOrWorkerGlobalScope/setTimeout", "Reasons for delays longer than specified")}} for examples.

+ +

Ensure that execution duration is shorter than interval frequency

+ +

If there is a possibility that your logic could take longer to execute than the interval time, it is recommended that you recursively call a named function using {{domxref("WindowOrWorkerGlobalScope.setTimeout", "setTimeout()")}}. For example, if using setInterval() to poll a remote server every 5 seconds, network latency, an unresponsive server, and a host of other issues could prevent the request from completing in its allotted time. As such, you may find yourself with queued up XHR requests that won't necessarily return in order.

+ +

In these cases, a recursive setTimeout() pattern is preferred:

+ +
(function loop(){
+   setTimeout(function() {
+      // Your logic here
+
+      loop();
+  }, delay);
+})();
+
+ +

In the above snippet, a named function loop() is declared and is immediately executed. loop() is recursively called inside setTimeout() after the logic has completed executing. While this pattern does not guarantee execution on a fixed interval, it does guarantee that the previous interval has completed before recursing.

+ +

Specifications

+ + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('HTML WHATWG', 'webappapis.html#dom-setinterval', 'WindowOrWorkerGlobalScope.setInterval()')}}{{Spec2("HTML WHATWG")}}Method moved to the WindowOrWorkerGlobalScope mixin in the latest spec.
{{SpecName("HTML WHATWG", "webappapis.html#dom-setinterval", "WindowTimers.setInterval()")}}{{Spec2("HTML WHATWG")}}Initial definition (DOM Level 0)
+ +

Browser compatibility

+ +
+ + +

{{Compat("api.WindowOrWorkerGlobalScope.setInterval")}}

+
+ +

See also

+ +
    +
  • JavaScript timers
  • +
  • {{domxref("WindowOrWorkerGlobalScope.setTimeout")}}
  • +
  • {{domxref("WindowOrWorkerGlobalScope.clearTimeout")}}
  • +
  • {{domxref("WindowOrWorkerGlobalScope.clearInterval")}}
  • +
  • {{domxref("window.requestAnimationFrame")}}
  • +
  • Daemons management
  • +
diff --git a/files/zh-tw/web/api/windoworworkerglobalscope/btoa/index.html b/files/zh-tw/web/api/windoworworkerglobalscope/btoa/index.html deleted file mode 100644 index 93d63b6010..0000000000 --- a/files/zh-tw/web/api/windoworworkerglobalscope/btoa/index.html +++ /dev/null @@ -1,136 +0,0 @@ ---- -title: WindowOrWorkerGlobalScope.btoa() -slug: Web/API/WindowOrWorkerGlobalScope/btoa -translation_of: Web/API/WindowOrWorkerGlobalScope/btoa ---- -

{{APIRef("HTML DOM")}}

- -

The WindowOrWorkerGlobalScope.btoa() method creates a {{glossary("Base64")}}-encoded ASCII string from a binary string (i.e., a {{jsxref("String")}} object in which each character in the string is treated as a byte of binary data).

- -

You can use this method to encode data which may otherwise cause communication problems, transmit it, then use the {{domxref("WindowOrWorkerGlobalScope.atob", "atob()")}} method to decode the data again. For example, you can encode control characters such as ASCII values 0 through 31.

- -

Syntax

- -
var encodedData = scope.btoa(stringToEncode);
- -

Parameters

- -
-
stringToEncode
-
The binary string to encode.
-
- -

Return value

- -

An ASCII string containing the Base64 representation of stringToEncode.

- -

Exceptions

- -
-
InvalidCharacterError
-
The string contained a character that did not fit in a single byte. See "Unicode strings" below for more detail.
-
- -

Example

- -
const encodedData = window.btoa('Hello, world'); // encode a string
-const decodedData = window.atob(encodedData); // decode the string
-
- -

Unicode strings

- -

The btoa() function takes a JavaScript string as a parameter. In JavaScript strings are represented using the UTF-16 character encoding: in this encoding, strings are represented as a sequence of 16-bit (2 byte) units. Every ASCII character fits into the first byte of one of these units, but many other characters don't.

- -

Base64, by design, expects binary data as its input. In terms of JavaScript strings, this means strings in which each character occupies only one byte. So if you pass a string into btoa() containing characters that occupy more than one byte, you will get an error, because this is not considered binary data:

- -
const ok = "a";
-console.log(ok.codePointAt(0).toString(16)); //   61: occupies < 1 byte
-
-const notOK = "✓"
-console.log(notOK.codePointAt(0).toString(16)); // 2713: occupies > 1 byte
-
-console.log(btoa(ok));    // YQ==
-console.log(btoa(notOK)); // error
- -

If you need to encode Unicode text as ASCII using btoa(), one option is to convert the string such that each 16-bit unit occupies only one byte. For example:

- -
// convert a Unicode string to a string in which
-// each 16-bit unit occupies only one byte
-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));
-}
-
-// a string that contains characters occupying > 1 byte
-const myString = "☸☹☺☻☼☾☿";
-
-const converted = toBinary(myString);
-const encoded = btoa(converted);
-console.log(encoded);                 // OCY5JjomOyY8Jj4mPyY=
-
- -

If you do this, of course you'll have to reverse the conversion on the decoded string:

- -
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);                // ☸☹☺☻☼☾☿
-
- -

Polyfill

- -

You can use a polyfill from https://github.com/MaxArt2501/base64-js/blob/master/base64.js for browsers that don't support it.

- -

Specifications

- - - - - - - - - - - - - - - - - - - - - - - - - - -
SpecificationStatusComment
{{SpecName('HTML WHATWG', '#dom-btoa', 'WindowOrWorkerGlobalScope.btoa()')}}{{Spec2('HTML WHATWG')}}Method moved to the WindowOrWorkerGlobalScope mixin in the latest spec.
{{SpecName('HTML5.1', '#dom-windowbase64-btoa', 'WindowBase64.btoa()')}}{{Spec2('HTML5.1')}}Snapshot of {{SpecName("HTML WHATWG")}}. No change.
{{SpecName("HTML5 W3C", "#dom-windowbase64-btoa", "WindowBase64.btoa()")}}{{Spec2('HTML5 W3C')}}Snapshot of {{SpecName("HTML WHATWG")}}. Creation of WindowBase64 (properties where on the target before it).
- -

Browser compatibility

- -
- - -

{{Compat("api.WindowOrWorkerGlobalScope.btoa")}}

-
- -

See also

- -
    -
  • data URIs
  • -
  • {{domxref("WindowOrWorkerGlobalScope.atob","atob()")}}
  • -
diff --git a/files/zh-tw/web/api/windoworworkerglobalscope/setinterval/index.html b/files/zh-tw/web/api/windoworworkerglobalscope/setinterval/index.html deleted file mode 100644 index 7685a8f754..0000000000 --- a/files/zh-tw/web/api/windoworworkerglobalscope/setinterval/index.html +++ /dev/null @@ -1,627 +0,0 @@ ---- -title: WindowOrWorkerGlobalScope.setInterval() -slug: Web/API/WindowOrWorkerGlobalScope/setInterval -translation_of: Web/API/WindowOrWorkerGlobalScope/setInterval ---- -
{{APIRef("HTML DOM")}}
- -

setInterval() 函式, {{domxref("Window")}} 與 {{domxref("Worker")}} 介面皆提供此一函式, 此函式作用為重複地執行一個函式呼叫或一個程式碼片斷, 每一次執行間隔固定的延遲時間. 此函式呼叫時將傳回一個間隔代碼(Interval ID)用以識別該間隔程序, 因此後續您可以呼叫 {{domxref("WindowOrWorkerGlobalScope.clearInterval", "clearInterval()")}} 函式移除該間隔程序. 此函式為由 {{domxref("WindowOrWorkerGlobalScope")}} 混合定義.

- -

Syntax

- -
var intervalID = scope.setInterval(func, [delay, arg1, arg2, ...]);
-var intervalID = scope.setInterval(code, [delay]);
-
- -

Parameters

- -
-
func
-
A {{jsxref("function")}} to be executed every delay milliseconds. The function is not passed any arguments, and no return value is expected.
-
code
-
An optional syntax allows you to include a string instead of a function, which is compiled and executed every delay milliseconds. This syntax is not recommended for the same reasons that make using {{jsxref("eval", "eval()")}} a security risk.
-
delay{{optional_inline}}
-
The time, in milliseconds (thousandths of a second), the timer should delay in between executions of the specified function or code. See {{anch("Delay restrictions")}} below for details on the permitted range of delay values.
-
arg1, ..., argN {{optional_inline}}
-
Additional arguments which are passed through to the function specified by func once the timer expires.
-
- -
-

Note: Passing additional arguments to setInterval() in the first syntax does not work in Internet Explorer 9 and earlier. If you want to enable this functionality on that browser, you must use a polyfill (see the Callback arguments section).

-
- -

Return value

- -

The returned intervalID is a numeric, non-zero value which identifies the timer created by the call to setInterval(); this value can be passed to {{domxref("WindowOrWorkerGlobalScope.clearInterval()")}} to cancel the timeout.

- -

It may be helpful to be aware that setInterval() and {{domxref("WindowOrWorkerGlobalScope.setTimeout", "setTimeout()")}} share the same pool of IDs, and that clearInterval() and {{domxref("WindowOrWorkerGlobalScope.clearTimeout", "clearTimeout()")}} can technically be used interchangeably. For clarity, however, you should try to always match them to avoid confusion when maintaining your code.

- -
Note: The delay argument is converted to a signed 32-bit integer. This effectively limits delay to 2147483647 ms, since it's specified as a signed integer in the IDL.
- -

Examples

- -

Example 1: Basic syntax

- -

The following example demonstrates setInterval()'s basic syntax.

- -
var intervalID = window.setInterval(myCallback, 500, 'Parameter 1', 'Parameter 2');
-
-function myCallback(a, b)
-{
- // Your code here
- // Parameters are purely optional.
- console.log(a);
- console.log(b);
-}
-
- -

Example 2: Alternating two colors

- -

The following example calls the flashtext() function once a second until the Stop button is pressed.

- -
<!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>
-
- -

Example 3: Typewriter simulation

- -

The following example simulates typewriter by first clearing and then slowly typing content into the NodeList that matches a specified group of selectors.

- -
<!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().

- -

Callback arguments

- -

As previously discussed, Internet Explorer versions 9 and below do not support the passing of arguments to the callback function in either setTimeout() or setInterval(). The following IE-specific code demonstrates a method for overcoming this limitation.  To use, simply add the following code to the top of your script.

- -
/*\
-|*|
-|*|  IE-specific polyfill that enables the passage of arbitrary arguments to the
-|*|  callback functions of javascript timers (HTML5 standard syntax).
-|*|
-|*|  https://developer.mozilla.org/en-US/docs/Web/API/window.setInterval
-|*|  https://developer.mozilla.org/User:fusionchess
-|*|
-|*|  Syntax:
-|*|  var timeoutID = window.setTimeout(func, delay[, arg1, arg2, ...]);
-|*|  var timeoutID = window.setTimeout(code, delay);
-|*|  var intervalID = window.setInterval(func, delay[, arg1, arg2, ...]);
-|*|  var intervalID = window.setInterval(code, delay);
-|*|
-\*/
-
-if (document.all && !window.setTimeout.isPolyfill) {
-  var __nativeST__ = window.setTimeout;
-  window.setTimeout = function (vCallback, nDelay /*, argumentToPass1, argumentToPass2, etc. */) {
-    var aArgs = Array.prototype.slice.call(arguments, 2);
-    return __nativeST__(vCallback instanceof Function ? function () {
-      vCallback.apply(null, aArgs);
-    } : vCallback, nDelay);
-  };
-  window.setTimeout.isPolyfill = true;
-}
-
-if (document.all && !window.setInterval.isPolyfill) {
-  var __nativeSI__ = window.setInterval;
-  window.setInterval = function (vCallback, nDelay /*, argumentToPass1, argumentToPass2, etc. */) {
-    var aArgs = Array.prototype.slice.call(arguments, 2);
-    return __nativeSI__(vCallback instanceof Function ? function () {
-      vCallback.apply(null, aArgs);
-    } : vCallback, nDelay);
-  };
-  window.setInterval.isPolyfill = true;
-}
-
- -

Another possibility is to use an anonymous function to call your callback, although this solution is a bit more expensive. Example:

- -
var intervalID = setInterval(function() { myFunc('one', 'two', 'three'); }, 1000);
- -

Another possibility is to use function's bind. Example:

- -
var intervalID = setInterval(function(arg1) {}.bind(undefined, 10), 1000);
- -

{{h3_gecko_minversion("Inactive tabs", "5.0")}}

- -

Starting in Gecko 5.0 {{geckoRelease("5.0")}}, intervals are clamped to fire no more often than once per second in inactive tabs.

- -

The "this" problem

- -

When you pass a method to setInterval() or any other function, it is invoked with the wrong this value. This problem is explained in detail in the JavaScript reference.

- -

Explanation

- -

Code executed by setInterval() runs in a separate execution context than the function from which it was called. As a consequence, the this keyword for the called function is set to the window (or global) object, it is not the same as the this value for the function that called setTimeout. See the following example (which uses setTimeout() instead of setInterval() – the problem, in fact, is the same for both timers):

- -
myArray = ['zero', 'one', 'two'];
-
-myArray.myMethod = function (sProperty) {
-    alert(arguments.length > 0 ? this[sProperty] : this);
-};
-
-myArray.myMethod(); // prints "zero,one,two"
-myArray.myMethod(1); // prints "one"
-setTimeout(myArray.myMethod, 1000); // prints "[object Window]" after 1 second
-setTimeout(myArray.myMethod, 1500, "1"); // prints "undefined" after 1,5 seconds
-// passing the 'this' object with .call won't work
-// because this will change the value of this inside setTimeout itself
-// while we want to change the value of this inside myArray.myMethod
-// in fact, it will be an error because setTimeout code expects this to be the window object:
-setTimeout.call(myArray, myArray.myMethod, 2000); // error: "NS_ERROR_XPC_BAD_OP_ON_WN_PROTO: Illegal operation on WrappedNative prototype object"
-setTimeout.call(myArray, myArray.myMethod, 2500, 2); // same error
-
- -

As you can see there are no ways to pass the this object to the callback function in the legacy JavaScript.

- -

A possible solution

- -

A possible way to solve the "this" problem is to replace the two native setTimeout() or setInterval() global functions with two non-native ones that enable their invocation through the Function.prototype.call method. The following example shows a possible replacement:

- -
// Enable the passage of the 'this' object through the JavaScript timers
-
-var __nativeST__ = window.setTimeout, __nativeSI__ = window.setInterval;
-
-window.setTimeout = function (vCallback, nDelay /*, argumentToPass1, argumentToPass2, etc. */) {
-  var oThis = this, aArgs = Array.prototype.slice.call(arguments, 2);
-  return __nativeST__(vCallback instanceof Function ? function () {
-    vCallback.apply(oThis, aArgs);
-  } : vCallback, nDelay);
-};
-
-window.setInterval = function (vCallback, nDelay /*, argumentToPass1, argumentToPass2, etc. */) {
-  var oThis = this, aArgs = Array.prototype.slice.call(arguments, 2);
-  return __nativeSI__(vCallback instanceof Function ? function () {
-    vCallback.apply(oThis, aArgs);
-  } : vCallback, nDelay);
-};
- -
These two replacements also enable the HTML5 standard passage of arbitrary arguments to the callback functions of timers in IE. So they can be used as non-standard-compliant polyfills also. See the callback arguments paragraph for a standard-compliant polyfill.
- -

New feature test:

- -
myArray = ['zero', 'one', 'two'];
-
-myArray.myMethod = function (sProperty) {
-    alert(arguments.length > 0 ? this[sProperty] : this);
-};
-
-setTimeout(alert, 1500, 'Hello world!'); // the standard use of setTimeout and setInterval is preserved, but...
-setTimeout.call(myArray, myArray.myMethod, 2000); // prints "zero,one,two" after 2 seconds
-setTimeout.call(myArray, myArray.myMethod, 2500, 2); // prints "two" after 2,5 seconds
-
- -

Another, more complex, solution for the this problem is the following framework.

- -
JavaScript 1.8.5 introduces the Function.prototype.bind() method, which lets you specify the value that should be used as this for all calls to a given function. This lets you easily bypass problems where it's unclear what this will be, depending on the context from which your function was called. Also, ES2015 supports arrow functions, with lexical this allowing us to write setInterval( () => this.myMethod) if we're inside myArray method.
- -

MiniDaemon - A framework for managing timers

- -

In pages requiring many timers, it can often be difficult to keep track of all of the running timer events. One approach to solving this problem is to store information about the state of a timer in an object. Following is a minimal example of such an abstraction. The constructor architecture explicitly avoids the use of closures. It also offers an alternative way to pass the this object to the callback function (see The "this" problem for details). The following code is also available on GitHub.

- -
For a more complex but still modular version of it (Daemon) see JavaScript Daemons Management. This more complex version is nothing but a big and scalable collection of methods for the Daemon constructor. However, the Daemon constructor itself is nothing but a clone of MiniDaemon with an added support for init and onstart functions declarable during the instantiation of the daemon. So the MiniDaemon framework remains the recommended way for simple animations, because Daemon without its collection of methods is essentially a clone of it.
- -

minidaemon.js

- -
/*\
-|*|
-|*|  :: MiniDaemon ::
-|*|
-|*|  Revision #2 - September 26, 2014
-|*|
-|*|  https://developer.mozilla.org/en-US/docs/Web/API/window.setInterval
-|*|  https://developer.mozilla.org/User:fusionchess
-|*|  https://github.com/madmurphy/minidaemon.js
-|*|
-|*|  This framework is released under the GNU Lesser General Public License, version 3 or later.
-|*|  http://www.gnu.org/licenses/lgpl-3.0.html
-|*|
-\*/
-
-function MiniDaemon (oOwner, fTask, nRate, nLen) {
-  if (!(this && this instanceof MiniDaemon)) { return; }
-  if (arguments.length < 2) { throw new TypeError('MiniDaemon - not enough arguments'); }
-  if (oOwner) { this.owner = oOwner; }
-  this.task = fTask;
-  if (isFinite(nRate) && nRate > 0) { this.rate = Math.floor(nRate); }
-  if (nLen > 0) { this.length = Math.floor(nLen); }
-}
-
-MiniDaemon.prototype.owner = null;
-MiniDaemon.prototype.task = null;
-MiniDaemon.prototype.rate = 100;
-MiniDaemon.prototype.length = Infinity;
-
-  /* These properties should be read-only */
-
-MiniDaemon.prototype.SESSION = -1;
-MiniDaemon.prototype.INDEX = 0;
-MiniDaemon.prototype.PAUSED = true;
-MiniDaemon.prototype.BACKW = true;
-
-  /* Global methods */
-
-MiniDaemon.forceCall = function (oDmn) {
-  oDmn.INDEX += oDmn.BACKW ? -1 : 1;
-  if (oDmn.task.call(oDmn.owner, oDmn.INDEX, oDmn.length, oDmn.BACKW) === false || oDmn.isAtEnd()) { oDmn.pause(); return false; }
-  return true;
-};
-
-  /* Instances methods */
-
-MiniDaemon.prototype.isAtEnd = function () {
-  return this.BACKW ? isFinite(this.length) && this.INDEX < 1 : this.INDEX + 1 > this.length;
-};
-
-MiniDaemon.prototype.synchronize = function () {
-  if (this.PAUSED) { return; }
-  clearInterval(this.SESSION);
-  this.SESSION = setInterval(MiniDaemon.forceCall, this.rate, this);
-};
-
-MiniDaemon.prototype.pause = function () {
-  clearInterval(this.SESSION);
-  this.PAUSED = true;
-};
-
-MiniDaemon.prototype.start = function (bReverse) {
-  var bBackw = Boolean(bReverse);
-  if (this.BACKW === bBackw && (this.isAtEnd() || !this.PAUSED)) { return; }
-  this.BACKW = bBackw;
-  this.PAUSED = false;
-  this.synchronize();
-};
-
- -
MiniDaemon passes arguments to the callback function. If you want to work on it with browsers that natively do not support this feature, use one of the methods proposed above.
- -

Syntax

- -

var myDaemon = new MiniDaemon(thisObject, callback[, rate[, length]]);

- -

Description

- -

Returns a JavaScript Object containing all information needed by an animation (like the this object, the callback function, the length, the frame-rate).

- -

Arguments

- -
-
thisObject
-
The this object on which the callback function is called. It can be an object or null.
-
callback
-
The function that is repeatedly invoked . It is called with three arguments: index (the iterative index of each invocation), length (the number of total invocations assigned to the daemon - finite or Infinity) and backwards (a boolean expressing whether the index is increasing or decreasing). It is something like callback.call(thisObject, index, length, backwards). If the callback function returns a false value the daemon is paused.
-
rate (optional)
-
The time lapse (in number of milliseconds) between each invocation. The default value is 100.
-
length (optional)
-
The total number of invocations. It can be a positive integer or Infinity. The default value is Infinity.
-
- -

MiniDaemon instances properties

- -
-
myDaemon.owner
-
The this object on which is executed the daemon (read/write). It can be an object or null.
-
myDaemon.task
-
The function that is repeatedly invoked (read/write). It is called with three arguments: index (the iterative index of each invocation), length (the number of total invocations assigned to the daemon - finite or Infinity) and backwards (a boolean expressing whether the index is decreasing or not) – see above. If the myDaemon.task function returns a false value the daemon is paused.
-
myDaemon.rate
-
The time lapse (in number of milliseconds) between each invocation (read/write).
-
myDaemon.length
-
The total number of invocations. It can be a positive integer or Infinity (read/write).
-
- -

MiniDaemon instances methods

- -
-
myDaemon.isAtEnd()
-
Returns a boolean expressing whether the daemon is at the start/end position or not.
-
myDaemon.synchronize()
-
Synchronize the timer of a started daemon with the time of its invocation.
-
myDaemon.pause()
-
Pauses the daemon.
-
myDaemon.start([reverse])
-
Starts the daemon forward (index of each invocation increasing) or backwards (index decreasing).
-
- -

MiniDaemon global object methods

- -
-
MiniDaemon.forceCall(minidaemon)
-
Forces a single callback to the minidaemon.task function regardless of the fact that the end has been reached or not. In any case the internal INDEX property is increased/decreased (depending on the actual direction of the process).
-
- -

Example usage

- -

Your HTML page:

- -
<!DOCTYPE html>
-<html>
-<head>
-  <meta charset="UTF-8" />
-  <title>MiniDaemin Example - MDN</title>
-  <script type="text/javascript" src="minidaemon.js"></script>
-  <style type="text/css">
-    #sample_div {
-      visibility: hidden;
-    }
-  </style>
-</head>
-
-<body>
-  <p>
-    <input type="button" onclick="fadeInOut.start(false /* optional */);" value="fade in" />
-    <input type="button" onclick="fadeInOut.start(true);" value="fade out">
-    <input type="button" onclick="fadeInOut.pause();" value="pause" />
-  </p>
-
-  <div id="sample_div">Some text here</div>
-
-  <script type="text/javascript">
-    function opacity (nIndex, nLength, bBackwards) {
-      this.style.opacity = nIndex / nLength;
-      if (bBackwards ? nIndex === 0 : nIndex === 1) {
-        this.style.visibility = bBackwards ? 'hidden' : 'visible';
-      }
-    }
-
-    var fadeInOut = new MiniDaemon(document.getElementById('sample_div'), opacity, 300, 8);
-  </script>
-</body>
-</html>
- -

View this example in action

- -

Usage notes

- -

The setInterval() function is commonly used to set a delay for functions that are executed again and again, such as animations. You can cancel the interval using {{domxref("WindowOrWorkerGlobalScope.clearInterval()")}}.

- -

If you wish to have your function called once after the specified delay, use {{domxref("WindowOrWorkerGlobalScope.setTimeout()")}}.

- -

Delay restrictions

- -

It's possible for intervals to be nested; that is, the callback for setInterval() can in turn call setInterval() to start another interval running, even though the first one is still going. To mitigate the potential impact this can have on performance, once intervals are nested beyond five levels deep, the browser will automatically enforce a 4 ms minimum value for the interval. Attempts to specify a value less than 4 ms in deeply-nested calls to setInterval() will be pinned to 4 ms.

- -

Browsers may enforce even more stringent minimum values for the interval under some circumstances, although these should not be common. Note also that the actual amount of time that elapses between calls to the callback may be longer than the given delay; see {{SectionOnPage("/en-US/docs/Web/API/WindowOrWorkerGlobalScope/setTimeout", "Reasons for delays longer than specified")}} for examples.

- -

Ensure that execution duration is shorter than interval frequency

- -

If there is a possibility that your logic could take longer to execute than the interval time, it is recommended that you recursively call a named function using {{domxref("WindowOrWorkerGlobalScope.setTimeout", "setTimeout()")}}. For example, if using setInterval() to poll a remote server every 5 seconds, network latency, an unresponsive server, and a host of other issues could prevent the request from completing in its allotted time. As such, you may find yourself with queued up XHR requests that won't necessarily return in order.

- -

In these cases, a recursive setTimeout() pattern is preferred:

- -
(function loop(){
-   setTimeout(function() {
-      // Your logic here
-
-      loop();
-  }, delay);
-})();
-
- -

In the above snippet, a named function loop() is declared and is immediately executed. loop() is recursively called inside setTimeout() after the logic has completed executing. While this pattern does not guarantee execution on a fixed interval, it does guarantee that the previous interval has completed before recursing.

- -

Specifications

- - - - - - - - - - - - - - - - - - - -
SpecificationStatusComment
{{SpecName('HTML WHATWG', 'webappapis.html#dom-setinterval', 'WindowOrWorkerGlobalScope.setInterval()')}}{{Spec2("HTML WHATWG")}}Method moved to the WindowOrWorkerGlobalScope mixin in the latest spec.
{{SpecName("HTML WHATWG", "webappapis.html#dom-setinterval", "WindowTimers.setInterval()")}}{{Spec2("HTML WHATWG")}}Initial definition (DOM Level 0)
- -

Browser compatibility

- -
- - -

{{Compat("api.WindowOrWorkerGlobalScope.setInterval")}}

-
- -

See also

- -
    -
  • JavaScript timers
  • -
  • {{domxref("WindowOrWorkerGlobalScope.setTimeout")}}
  • -
  • {{domxref("WindowOrWorkerGlobalScope.clearTimeout")}}
  • -
  • {{domxref("WindowOrWorkerGlobalScope.clearInterval")}}
  • -
  • {{domxref("window.requestAnimationFrame")}}
  • -
  • Daemons management
  • -
-- cgit v1.2.3-54-g00ecf From dda635dd6182e36ba9ac07810014cf15cf47e50a Mon Sep 17 00:00:00 2001 From: MDN Date: Thu, 2 Sep 2021 00:46:31 +0000 Subject: [CRON] sync translated content --- files/de/_redirects.txt | 1 + files/de/_wikihistory.json | 14 +++++----- files/de/conflicting/web/css/index.html | 26 ++++++++++++++++++ files/de/web/css/tools/index.html | 25 ----------------- files/es/_redirects.txt | 3 ++- files/es/_wikihistory.json | 12 ++++----- files/es/conflicting/web/css/index.html | 29 ++++++++++++++++++++ files/es/web/css/tools/index.html | 29 -------------------- files/fr/_redirects.txt | 3 ++- files/fr/_wikihistory.json | 14 +++++----- .../index.html | 21 +++++++++++++++ files/fr/web/css/tools/index.html | 21 --------------- files/ja/_redirects.txt | 1 + files/ja/_wikihistory.json | 14 +++++----- files/ja/conflicting/web/css/index.html | 31 ++++++++++++++++++++++ files/ja/web/css/tools/index.html | 30 --------------------- files/pt-br/_redirects.txt | 1 + files/pt-br/_wikihistory.json | 14 +++++----- files/pt-br/conflicting/web/css/index.html | 31 ++++++++++++++++++++++ files/pt-br/web/css/tools/index.html | 30 --------------------- files/zh-cn/_redirects.txt | 1 + files/zh-cn/_wikihistory.json | 20 +++++++------- files/zh-cn/conflicting/web/css/index.html | 28 +++++++++++++++++++ files/zh-cn/web/css/tools/index.html | 27 ------------------- 24 files changed, 218 insertions(+), 208 deletions(-) create mode 100644 files/de/conflicting/web/css/index.html delete mode 100644 files/de/web/css/tools/index.html create mode 100644 files/es/conflicting/web/css/index.html delete mode 100644 files/es/web/css/tools/index.html create mode 100644 files/fr/conflicting/web/css_c2c099599c0a58c69d1390033045f244/index.html delete mode 100644 files/fr/web/css/tools/index.html create mode 100644 files/ja/conflicting/web/css/index.html delete mode 100644 files/ja/web/css/tools/index.html create mode 100644 files/pt-br/conflicting/web/css/index.html delete mode 100644 files/pt-br/web/css/tools/index.html create mode 100644 files/zh-cn/conflicting/web/css/index.html delete mode 100644 files/zh-cn/web/css/tools/index.html (limited to 'files/es/_wikihistory.json') diff --git a/files/de/_redirects.txt b/files/de/_redirects.txt index 6a5b8a39f0..1e1a223b58 100644 --- a/files/de/_redirects.txt +++ b/files/de/_redirects.txt @@ -531,6 +531,7 @@ /de/docs/Web/CSS/Pseudoklasse /de/docs/Web/CSS/Pseudo-classes /de/docs/Web/CSS/Referenz /de/docs/Web/CSS/Reference /de/docs/Web/CSS/Spezifität /de/docs/Web/CSS/Specificity +/de/docs/Web/CSS/Tools /de/docs/conflicting/Web/CSS /de/docs/Web/CSS/Vererbung /de/docs/Web/CSS/inheritance /de/docs/Web/CSS/Wertdefinitionssyntax /de/docs/Web/CSS/Value_definition_syntax /de/docs/Web/CSS/attr /de/docs/Web/CSS/attr() diff --git a/files/de/_wikihistory.json b/files/de/_wikihistory.json index 6e9006333c..6c44b44041 100644 --- a/files/de/_wikihistory.json +++ b/files/de/_wikihistory.json @@ -5602,13 +5602,6 @@ "Sebastianz" ] }, - "Web/CSS/Tools": { - "modified": "2019-03-23T22:43:38.676Z", - "contributors": [ - "Sebastianz", - "creativenitish" - ] - }, "Web/CSS/Tools/Linear-gradient_Generator": { "modified": "2019-03-23T22:43:38.482Z", "contributors": [ @@ -13590,6 +13583,13 @@ "eminor" ] }, + "conflicting/Web/CSS": { + "modified": "2019-03-23T22:43:38.676Z", + "contributors": [ + "Sebastianz", + "creativenitish" + ] + }, "conflicting/Web/CSS/::placeholder": { "modified": "2019-03-23T23:08:23.797Z", "contributors": [ diff --git a/files/de/conflicting/web/css/index.html b/files/de/conflicting/web/css/index.html new file mode 100644 index 0000000000..0cdc9d3d44 --- /dev/null +++ b/files/de/conflicting/web/css/index.html @@ -0,0 +1,26 @@ +--- +title: Tools +slug: conflicting/Web/CSS +tags: + - CSS +translation_of: Web/CSS/Tools +original_slug: Web/CSS/Tools +--- +

CSS bietet eine Reihe mächtiger Features, die knifflig in der Anwendung sein können oder eine Reihe von Parametern haben, sodass es hilfreich ist, diese während an ihnen gearbeitet wird, zu visualisieren. Dieses Seite bietet Links zu verschiedenen nützlichen Werkzeugen, die helfen, das CSS unter Verwendung dieser Features zu erstellen, um den Inhalt zu stylen.

+ +

{{LandingPageListSubpages}}

+ +

Weitere Werkzeuge

+ +
    +
  • +

    CSS Animation - Stylie

    +
  • +
  • Um die Gerätedarstellungsinformationen zu überprüfen (hilfreich in {{Glossary("Responsive Web Design")}}) - mydevice.io
  • +
+ +

Siehe auch

+ + diff --git a/files/de/web/css/tools/index.html b/files/de/web/css/tools/index.html deleted file mode 100644 index f107c81ddb..0000000000 --- a/files/de/web/css/tools/index.html +++ /dev/null @@ -1,25 +0,0 @@ ---- -title: Tools -slug: Web/CSS/Tools -tags: - - CSS -translation_of: Web/CSS/Tools ---- -

CSS bietet eine Reihe mächtiger Features, die knifflig in der Anwendung sein können oder eine Reihe von Parametern haben, sodass es hilfreich ist, diese während an ihnen gearbeitet wird, zu visualisieren. Dieses Seite bietet Links zu verschiedenen nützlichen Werkzeugen, die helfen, das CSS unter Verwendung dieser Features zu erstellen, um den Inhalt zu stylen.

- -

{{LandingPageListSubpages}}

- -

Weitere Werkzeuge

- -
    -
  • -

    CSS Animation - Stylie

    -
  • -
  • Um die Gerätedarstellungsinformationen zu überprüfen (hilfreich in {{Glossary("Responsive Web Design")}}) - mydevice.io
  • -
- -

Siehe auch

- - diff --git a/files/es/_redirects.txt b/files/es/_redirects.txt index 393d653e5f..144e880d55 100644 --- a/files/es/_redirects.txt +++ b/files/es/_redirects.txt @@ -1664,7 +1664,7 @@ /es/docs/Web/CSS/Elemento_reemplazo /es/docs/Web/CSS/Replaced_element /es/docs/Web/CSS/Especificidad /es/docs/Web/CSS/Specificity /es/docs/Web/CSS/Gradiente /es/docs/Web/CSS/gradient -/es/docs/Web/CSS/Herramientas /es/docs/Web/CSS/Tools +/es/docs/Web/CSS/Herramientas /es/docs/conflicting/Web/CSS /es/docs/Web/CSS/Introducción/Content /es/docs/Learn/CSS/Howto/Generated_content /es/docs/Web/CSS/Introducción/Media /es/docs/Web/Progressive_web_apps/Responsive/Media_types /es/docs/Web/CSS/Preguntas_frecuentes_sobre_CSS /es/docs/Learn/CSS/Howto/CSS_FAQ @@ -1681,6 +1681,7 @@ /es/docs/Web/CSS/Selectores_hermanos_generales /es/docs/Web/CSS/General_sibling_combinator /es/docs/Web/CSS/Sintaxis_definición_de_valor /es/docs/Web/CSS/Value_definition_syntax /es/docs/Web/CSS/Texto_CSS /es/docs/Web/CSS/CSS_Text +/es/docs/Web/CSS/Tools /es/docs/conflicting/Web/CSS /es/docs/Web/CSS/Transiciones_de_CSS /es/docs/Web/CSS/CSS_Transitions/Using_CSS_transitions /es/docs/Web/CSS/Usando_animaciones_CSS /es/docs/Web/CSS/CSS_Animations/Using_CSS_animations /es/docs/Web/CSS/Using_CSS_transforms /es/docs/Web/CSS/CSS_Transforms/Using_CSS_transforms diff --git a/files/es/_wikihistory.json b/files/es/_wikihistory.json index 3808f684eb..be405acc83 100644 --- a/files/es/_wikihistory.json +++ b/files/es/_wikihistory.json @@ -11192,12 +11192,6 @@ "Derhks" ] }, - "Web/CSS/Tools": { - "modified": "2019-03-23T22:28:04.142Z", - "contributors": [ - "arturoblack" - ] - }, "Web/CSS/Tutorials": { "modified": "2019-03-23T22:52:34.225Z", "contributors": [ @@ -21464,6 +21458,12 @@ "Jeremie" ] }, + "conflicting/Web/CSS": { + "modified": "2019-03-23T22:28:04.142Z", + "contributors": [ + "arturoblack" + ] + }, "conflicting/Web/CSS/::placeholder": { "modified": "2019-03-23T22:29:22.118Z", "contributors": [ diff --git a/files/es/conflicting/web/css/index.html b/files/es/conflicting/web/css/index.html new file mode 100644 index 0000000000..988256afbd --- /dev/null +++ b/files/es/conflicting/web/css/index.html @@ -0,0 +1,29 @@ +--- +title: Herramientas +slug: conflicting/Web/CSS +tags: + - CSS +translation_of: Web/CSS/Tools +original_slug: Web/CSS/Tools +--- +
 
+ +

CSS ofrece una serie de características poderosas que puede ser difíciles de usar, o tener un gran número de parámetros, por lo que es muy útil visualizarlos mientras se trabaja en ellos. Esta página ofrece enlaces a una serie de herramientas que le ayudarán a construir sus estilos usando estas caracteristicas.

+ +

{{LandingPageListSubpages}}

+ +

Otras herramientas

+ +
    +
  • +

    Animación CSS - Stylie

    +
  • +
  • Para comprobar la información de la pantalla del dispositivo (helpful in {{Glossary("responsive web design")}}) - mydevice.io
  • +
  • Menus CSS- cssmenumaker.com
  • +
+ +

Temas relacionados

+ + diff --git a/files/es/web/css/tools/index.html b/files/es/web/css/tools/index.html deleted file mode 100644 index 3ea9e20a3f..0000000000 --- a/files/es/web/css/tools/index.html +++ /dev/null @@ -1,29 +0,0 @@ ---- -title: Herramientas -slug: Web/CSS/Tools -tags: - - CSS -translation_of: Web/CSS/Tools -original_slug: Web/CSS/Herramientas ---- -
 
- -

CSS ofrece una serie de características poderosas que puede ser difíciles de usar, o tener un gran número de parámetros, por lo que es muy útil visualizarlos mientras se trabaja en ellos. Esta página ofrece enlaces a una serie de herramientas que le ayudarán a construir sus estilos usando estas caracteristicas.

- -

{{LandingPageListSubpages}}

- -

Otras herramientas

- -
    -
  • -

    Animación CSS - Stylie

    -
  • -
  • Para comprobar la información de la pantalla del dispositivo (helpful in {{Glossary("responsive web design")}}) - mydevice.io
  • -
  • Menus CSS- cssmenumaker.com
  • -
- -

Temas relacionados

- - diff --git a/files/fr/_redirects.txt b/files/fr/_redirects.txt index 0e2dca875d..2e6bf4cbba 100644 --- a/files/fr/_redirects.txt +++ b/files/fr/_redirects.txt @@ -4114,7 +4114,7 @@ /fr/docs/Web/CSS/Média/Visuel /fr/docs/Web/CSS/@media /fr/docs/Web/CSS/Média_Paginé /fr/docs/Web/CSS/Paged_Media /fr/docs/Web/CSS/Média_paginés /fr/docs/Web/CSS/Paged_Media -/fr/docs/Web/CSS/Outils /fr/docs/Web/CSS/Tools +/fr/docs/Web/CSS/Outils /fr/docs/conflicting/Web/CSS_c2c099599c0a58c69d1390033045f244 /fr/docs/Web/CSS/Outils/Générateur_de_courbe_de_Bézier /fr/docs/orphaned/Web/CSS/Tools/Cubic_Bezier_Generator /fr/docs/Web/CSS/Outils/Générateur_de_dégradés_linéaires /fr/docs/Web/CSS/Tools/Linear-gradient_Generator /fr/docs/Web/CSS/Propriétés_raccourcies /fr/docs/Web/CSS/Shorthand_properties @@ -4150,6 +4150,7 @@ /fr/docs/Web/CSS/Sélecteurs_descendant /fr/docs/Web/CSS/Descendant_combinator /fr/docs/Web/CSS/Sélecteurs_enfant /fr/docs/Web/CSS/Child_combinator /fr/docs/Web/CSS/Sélecteurs_universels /fr/docs/Web/CSS/Universal_selectors +/fr/docs/Web/CSS/Tools /fr/docs/conflicting/Web/CSS_c2c099599c0a58c69d1390033045f244 /fr/docs/Web/CSS/Tools/Cubic_Bezier_Generator /fr/docs/orphaned/Web/CSS/Tools/Cubic_Bezier_Generator /fr/docs/Web/CSS/Tools/Générateur_de_courbe_de_Bézier /fr/docs/orphaned/Web/CSS/Tools/Cubic_Bezier_Generator /fr/docs/Web/CSS/Tools/Générateur_de_dégradés_linéaires /fr/docs/Web/CSS/Tools/Linear-gradient_Generator diff --git a/files/fr/_wikihistory.json b/files/fr/_wikihistory.json index ccfb379d40..121a997e06 100644 --- a/files/fr/_wikihistory.json +++ b/files/fr/_wikihistory.json @@ -25688,13 +25688,6 @@ "FredB" ] }, - "Web/CSS/Tools": { - "modified": "2019-04-06T13:47:45.843Z", - "contributors": [ - "SphinxKnight", - "velvel53" - ] - }, "Web/CSS/Tools/Linear-gradient_Generator": { "modified": "2019-04-06T13:48:01.466Z", "contributors": [ @@ -43607,6 +43600,13 @@ "ThePrisoner" ] }, + "conflicting/Web/CSS_c2c099599c0a58c69d1390033045f244": { + "modified": "2019-04-06T13:47:45.843Z", + "contributors": [ + "SphinxKnight", + "velvel53" + ] + }, "conflicting/Web/Guide": { "modified": "2019-03-24T00:13:07.123Z", "contributors": [ diff --git a/files/fr/conflicting/web/css_c2c099599c0a58c69d1390033045f244/index.html b/files/fr/conflicting/web/css_c2c099599c0a58c69d1390033045f244/index.html new file mode 100644 index 0000000000..84516f2356 --- /dev/null +++ b/files/fr/conflicting/web/css_c2c099599c0a58c69d1390033045f244/index.html @@ -0,0 +1,21 @@ +--- +title: Outils +slug: conflicting/Web/CSS_c2c099599c0a58c69d1390033045f244 +tags: + - CSS + - Outils +translation_of: Web/CSS/Tools +original_slug: Web/CSS/Tools +--- +

CSS fournit de nombreuses fonctionnalités qui peuvent être paramétrées avec différents facteurs. Il est donc utile de pouvoir visualiser ces paramètres lorsqu'on manipule ces propriétés. Cette page indique différents outils qui pourront vous être utiles lorsque vous construirez vos feuilles de style avec ces fonctionnalités.

+ +

{{LandingPageListSubpages}}

+ +

Autres outils

+ +
    +
  • Stylie pour les animations
  • +
  • Connaître les informations d'affichage d'un appareil (utile pour la conception de sites adaptatifs) : mydevice.io
  • +
  • Construire des menus CSS - cssmenumaker.com
  • +
  • Un linter CSS qui permet de respecter des conventions homogènes et d'éviter des erreurs dans les feuilles de style - stylelint
  • +
diff --git a/files/fr/web/css/tools/index.html b/files/fr/web/css/tools/index.html deleted file mode 100644 index ac24b6e9ee..0000000000 --- a/files/fr/web/css/tools/index.html +++ /dev/null @@ -1,21 +0,0 @@ ---- -title: Outils -slug: Web/CSS/Tools -tags: - - CSS - - Outils -translation_of: Web/CSS/Tools -original_slug: Web/CSS/Outils ---- -

CSS fournit de nombreuses fonctionnalités qui peuvent être paramétrées avec différents facteurs. Il est donc utile de pouvoir visualiser ces paramètres lorsqu'on manipule ces propriétés. Cette page indique différents outils qui pourront vous être utiles lorsque vous construirez vos feuilles de style avec ces fonctionnalités.

- -

{{LandingPageListSubpages}}

- -

Autres outils

- -
    -
  • Stylie pour les animations
  • -
  • Connaître les informations d'affichage d'un appareil (utile pour la conception de sites adaptatifs) : mydevice.io
  • -
  • Construire des menus CSS - cssmenumaker.com
  • -
  • Un linter CSS qui permet de respecter des conventions homogènes et d'éviter des erreurs dans les feuilles de style - stylelint
  • -
diff --git a/files/ja/_redirects.txt b/files/ja/_redirects.txt index 6117892834..de680f387d 100644 --- a/files/ja/_redirects.txt +++ b/files/ja/_redirects.txt @@ -3683,6 +3683,7 @@ /ja/docs/Web/CSS/Reference/@viewport/zoom /ja/docs/Web/CSS/@viewport /ja/docs/Web/CSS/Reference/Mozilla_Extensions /ja/docs/Web/CSS/Mozilla_Extensions /ja/docs/Web/CSS/Scaling_background_images /ja/docs/Web/CSS/CSS_Backgrounds_and_Borders/Resizing_background_images +/ja/docs/Web/CSS/Tools /ja/docs/conflicting/Web/CSS /ja/docs/Web/CSS/Understanding_z_index /ja/docs/Web/CSS/CSS_Positioning/Understanding_z_index /ja/docs/Web/CSS/Understanding_z_index/Adding_z-index /ja/docs/Web/CSS/CSS_Positioning/Understanding_z_index/Adding_z-index /ja/docs/Web/CSS/Understanding_z_index/Stacking_and_float /ja/docs/Web/CSS/CSS_Positioning/Understanding_z_index/Stacking_and_float diff --git a/files/ja/_wikihistory.json b/files/ja/_wikihistory.json index 71a15c0761..44f4c575d1 100644 --- a/files/ja/_wikihistory.json +++ b/files/ja/_wikihistory.json @@ -29309,13 +29309,6 @@ "sii" ] }, - "Web/CSS/Tools": { - "modified": "2020-07-21T12:48:32.485Z", - "contributors": [ - "mfuji09", - "sii" - ] - }, "Web/CSS/Type_selectors": { "modified": "2020-10-15T21:20:42.015Z", "contributors": [ @@ -48609,6 +48602,13 @@ "Jeremie" ] }, + "conflicting/Web/CSS": { + "modified": "2020-07-21T12:48:32.485Z", + "contributors": [ + "mfuji09", + "sii" + ] + }, "orphaned/Building_a_Mozilla_Distribution": { "modified": "2019-03-23T23:49:07.062Z", "contributors": [ diff --git a/files/ja/conflicting/web/css/index.html b/files/ja/conflicting/web/css/index.html new file mode 100644 index 0000000000..9585f457ed --- /dev/null +++ b/files/ja/conflicting/web/css/index.html @@ -0,0 +1,31 @@ +--- +title: ツール +slug: conflicting/Web/CSS +tags: + - CSS + - Guide + - NeedsUpdate + - ガイド +translation_of: Web/CSS/Tools +original_slug: Web/CSS/Tools +--- +
+ +

CSS は強力な機能を多数提供していますが、その中には使いこなすのが面倒だったり、引数が多かったりするので、作業をしながら視覚化できると便利です。このページでは、これらの機能を使ってコンテンツのスタイルを整えるための CSS を構築するのに役立つ便利なツールへのリンクをいくつか紹介しています。

+ +

{{LandingPageListSubpages}}

+ +

その他のツール

+ +
    +
  • CSS アニメーション - Stylie
  • +
  • 端末のディスプレイ情報を調べる ({{Glossary("responsive web design")}} で役立ちます) - mydevice.io
  • +
  • CSS メニュー - cssmenumaker.com
  • +
  • 強力でモダンな CSS リンターで、一貫性のある規約を施行し、スタイルシートでのエラーを回避するのに役立ちます - stylelint
  • +
+ +

関連情報

+ + diff --git a/files/ja/web/css/tools/index.html b/files/ja/web/css/tools/index.html deleted file mode 100644 index fb51e9d15d..0000000000 --- a/files/ja/web/css/tools/index.html +++ /dev/null @@ -1,30 +0,0 @@ ---- -title: ツール -slug: Web/CSS/Tools -tags: - - CSS - - Guide - - NeedsUpdate - - ガイド -translation_of: Web/CSS/Tools ---- -
- -

CSS は強力な機能を多数提供していますが、その中には使いこなすのが面倒だったり、引数が多かったりするので、作業をしながら視覚化できると便利です。このページでは、これらの機能を使ってコンテンツのスタイルを整えるための CSS を構築するのに役立つ便利なツールへのリンクをいくつか紹介しています。

- -

{{LandingPageListSubpages}}

- -

その他のツール

- -
    -
  • CSS アニメーション - Stylie
  • -
  • 端末のディスプレイ情報を調べる ({{Glossary("responsive web design")}} で役立ちます) - mydevice.io
  • -
  • CSS メニュー - cssmenumaker.com
  • -
  • 強力でモダンな CSS リンターで、一貫性のある規約を施行し、スタイルシートでのエラーを回避するのに役立ちます - stylelint
  • -
- -

関連情報

- - diff --git a/files/pt-br/_redirects.txt b/files/pt-br/_redirects.txt index d8fbb3ee68..c8c1a6bb45 100644 --- a/files/pt-br/_redirects.txt +++ b/files/pt-br/_redirects.txt @@ -593,6 +593,7 @@ /pt-BR/docs/Web/CSS/Seletor_universal /pt-BR/docs/Web/CSS/Universal_selectors /pt-BR/docs/Web/CSS/Seletores_CSS /pt-BR/docs/Web/CSS/CSS_Selectors /pt-BR/docs/Web/CSS/Sintexe_valor /pt-BR/docs/Web/CSS/Value_definition_syntax +/pt-BR/docs/Web/CSS/Tools /pt-BR/docs/conflicting/Web/CSS /pt-BR/docs/Web/CSS/Tools/Border-image_generator /pt-BR/docs/Web/CSS/CSS_Backgrounds_and_Borders/Border-image_generator /pt-BR/docs/Web/CSS/Tools/Border-radius_generator /pt-BR/docs/Web/CSS/CSS_Backgrounds_and_Borders/Border-radius_generator /pt-BR/docs/Web/CSS/Using_CSS_variables /pt-BR/docs/Web/CSS/Using_CSS_custom_properties diff --git a/files/pt-br/_wikihistory.json b/files/pt-br/_wikihistory.json index 2c13008b4e..d9f57768b3 100644 --- a/files/pt-br/_wikihistory.json +++ b/files/pt-br/_wikihistory.json @@ -7981,13 +7981,6 @@ "fvargaspf@gmail.com" ] }, - "Web/CSS/Tools": { - "modified": "2019-03-23T23:07:41.210Z", - "contributors": [ - "hlays", - "velvel53" - ] - }, "Web/CSS/Type_selectors": { "modified": "2020-10-15T22:32:30.449Z", "contributors": [ @@ -16469,6 +16462,13 @@ "caio.rrs" ] }, + "conflicting/Web/CSS": { + "modified": "2019-03-23T23:07:41.210Z", + "contributors": [ + "hlays", + "velvel53" + ] + }, "conflicting/Web/CSS/CSS_Flexible_Box_Layout/Basic_Concepts_of_Flexbox": { "modified": "2019-09-08T09:50:19.292Z", "contributors": [ diff --git a/files/pt-br/conflicting/web/css/index.html b/files/pt-br/conflicting/web/css/index.html new file mode 100644 index 0000000000..82fa64bdf2 --- /dev/null +++ b/files/pt-br/conflicting/web/css/index.html @@ -0,0 +1,31 @@ +--- +title: Ferramentas +slug: conflicting/Web/CSS +tags: + - CSS + - NeedsContent +translation_of: Web/CSS/Tools +original_slug: Web/CSS/Tools +--- +
{{Draft}}
+ +

O CSS oferece diversos recursos poderosos e um grande número de parâmetros que, às vezes, podem ser difíceis de usar. Então, é bem melhor quando você pode visualizá-los enquanto trabalha com eles.

+ +

Esta página oferece links para várias ferramentas úteis que irão te ajudar a criar o CSS para estilizar seu conteúdo usando esses recursos.

+ +

{{LandingPageListSubpages}}

+ +

Outras ferramentas

+ +
    +
  • Animação em CSS - Stylie
  • +
  • Para verificar as informações de exibição do dispositivo (útil para {{Glossary("web design responsivo")}}) - mydevice.io
  • +
  • Menus CSS - cssmenumaker.com
  • +
  • Um poderoso e moderno linter CSS que ajuda a impor convenções consistentes e evitar erros em suas folhas de estilo - stylelint
  • +
+ +

Veja também

+ + diff --git a/files/pt-br/web/css/tools/index.html b/files/pt-br/web/css/tools/index.html deleted file mode 100644 index 2e17ae96d5..0000000000 --- a/files/pt-br/web/css/tools/index.html +++ /dev/null @@ -1,30 +0,0 @@ ---- -title: Ferramentas -slug: Web/CSS/Tools -tags: - - CSS - - NeedsContent -translation_of: Web/CSS/Tools ---- -
{{Draft}}
- -

O CSS oferece diversos recursos poderosos e um grande número de parâmetros que, às vezes, podem ser difíceis de usar. Então, é bem melhor quando você pode visualizá-los enquanto trabalha com eles.

- -

Esta página oferece links para várias ferramentas úteis que irão te ajudar a criar o CSS para estilizar seu conteúdo usando esses recursos.

- -

{{LandingPageListSubpages}}

- -

Outras ferramentas

- -
    -
  • Animação em CSS - Stylie
  • -
  • Para verificar as informações de exibição do dispositivo (útil para {{Glossary("web design responsivo")}}) - mydevice.io
  • -
  • Menus CSS - cssmenumaker.com
  • -
  • Um poderoso e moderno linter CSS que ajuda a impor convenções consistentes e evitar erros em suas folhas de estilo - stylelint
  • -
- -

Veja também

- - diff --git a/files/zh-cn/_redirects.txt b/files/zh-cn/_redirects.txt index f625f0a1c0..c9a3dcc7c3 100644 --- a/files/zh-cn/_redirects.txt +++ b/files/zh-cn/_redirects.txt @@ -1714,6 +1714,7 @@ /zh-CN/docs/Web/CSS/Reference/Webkit_Extensions /zh-CN/docs/Web/CSS/WebKit_Extensions /zh-CN/docs/Web/CSS/Reference/background-blend-mode /zh-CN/docs/Web/CSS/background-blend-mode /zh-CN/docs/Web/CSS/Reference/mix-blend-mode /zh-CN/docs/Web/CSS/mix-blend-mode +/zh-CN/docs/Web/CSS/Tools /zh-CN/docs/conflicting/Web/CSS /zh-CN/docs/Web/CSS/Tutorials/Using_CSS_transforms /zh-CN/docs/Web/CSS/CSS_Transforms/Using_CSS_transforms /zh-CN/docs/Web/CSS/Understanding_z-index /zh-CN/docs/Web/CSS/CSS_Positioning/Understanding_z_index /zh-CN/docs/Web/CSS/Understanding_z-index/Adding_z-index /zh-CN/docs/Web/CSS/CSS_Positioning/Understanding_z_index/Adding_z-index diff --git a/files/zh-cn/_wikihistory.json b/files/zh-cn/_wikihistory.json index f4f8937676..3e599cf40f 100644 --- a/files/zh-cn/_wikihistory.json +++ b/files/zh-cn/_wikihistory.json @@ -27262,16 +27262,6 @@ "yan" ] }, - "Web/CSS/Tools": { - "modified": "2019-03-23T22:29:45.280Z", - "contributors": [ - "runyul", - "pluwen", - "edwards1101", - "lucia007", - "lunix01" - ] - }, "Web/CSS/Tutorials": { "modified": "2019-03-23T23:32:32.218Z", "contributors": [ @@ -47394,6 +47384,16 @@ "qianzhangcheng" ] }, + "conflicting/Web/CSS": { + "modified": "2019-03-23T22:29:45.280Z", + "contributors": [ + "runyul", + "pluwen", + "edwards1101", + "lucia007", + "lunix01" + ] + }, "conflicting/Web/CSS/::placeholder": { "modified": "2019-03-23T23:21:18.757Z", "contributors": [ diff --git a/files/zh-cn/conflicting/web/css/index.html b/files/zh-cn/conflicting/web/css/index.html new file mode 100644 index 0000000000..007a716edb --- /dev/null +++ b/files/zh-cn/conflicting/web/css/index.html @@ -0,0 +1,28 @@ +--- +title: 工具 +slug: conflicting/Web/CSS +tags: + - CSS +translation_of: Web/CSS/Tools +original_slug: Web/CSS/Tools +--- +
CSS提供了许多强大的功能,但这些功能要么可能很难使用,要么有许多参数,因此在使用它们时,能够可视化它们是有帮助的。此页面提供了一些有用的工具的链接,这些工具将帮助您使用这些功能构建 CSS 来设计您的内容。
+ +

 

+ +

{{LandingPageListSubpages}}

+ +

其他工具

+ +
    +
  • CSS 动画- Stylie
  • +
  • 查看设备的显示信息(从 {{Glossary("响应式网页设计")}}处得到帮助) - mydevice.io
  • +
  • CSS 菜单- cssmenumaker.com
  • +
  • 一个 强大并现代化的 CSS linter 可以帮助你实现统一约定并避免样式表中的错误 - stylelint
  • +
+ +

相关主题

+ + diff --git a/files/zh-cn/web/css/tools/index.html b/files/zh-cn/web/css/tools/index.html deleted file mode 100644 index a4c348fb36..0000000000 --- a/files/zh-cn/web/css/tools/index.html +++ /dev/null @@ -1,27 +0,0 @@ ---- -title: 工具 -slug: Web/CSS/Tools -tags: - - CSS -translation_of: Web/CSS/Tools ---- -
CSS提供了许多强大的功能,但这些功能要么可能很难使用,要么有许多参数,因此在使用它们时,能够可视化它们是有帮助的。此页面提供了一些有用的工具的链接,这些工具将帮助您使用这些功能构建 CSS 来设计您的内容。
- -

 

- -

{{LandingPageListSubpages}}

- -

其他工具

- -
    -
  • CSS 动画- Stylie
  • -
  • 查看设备的显示信息(从 {{Glossary("响应式网页设计")}}处得到帮助) - mydevice.io
  • -
  • CSS 菜单- cssmenumaker.com
  • -
  • 一个 强大并现代化的 CSS linter 可以帮助你实现统一约定并避免样式表中的错误 - stylelint
  • -
- -

相关主题

- - -- cgit v1.2.3-54-g00ecf From 5b3849c9e361be47aa718c437be1ed4430ba6dd7 Mon Sep 17 00:00:00 2001 From: MDN Date: Fri, 3 Sep 2021 00:46:48 +0000 Subject: [CRON] sync translated content --- files/de/_redirects.txt | 1 + files/de/_wikihistory.json | 2 +- files/de/web/demos/index.html | 155 +++++++++++++ .../web/demos_of_open_web_technologies/index.html | 154 ------------- files/es/_redirects.txt | 1 + files/es/_wikihistory.json | 2 +- files/es/web/demos/index.html | 162 ++++++++++++++ .../web/demos_of_open_web_technologies/index.html | 161 -------------- files/fr/_redirects.txt | 3 +- files/fr/_wikihistory.json | 2 +- files/fr/web/demos/index.html | 169 ++++++++++++++ .../web/demos_of_open_web_technologies/index.html | 169 -------------- files/ja/_redirects.txt | 1 + files/ja/_wikihistory.json | 2 +- files/ja/web/demos/index.html | 148 +++++++++++++ .../web/demos_of_open_web_technologies/index.html | 147 ------------- files/pt-br/_redirects.txt | 1 + files/pt-br/_wikihistory.json | 2 +- files/pt-br/web/demos/index.html | 242 +++++++++++++++++++++ .../web/demos_of_open_web_technologies/index.html | 241 -------------------- files/zh-cn/_redirects.txt | 3 +- files/zh-cn/_wikihistory.json | 2 +- files/zh-cn/web/demos/index.html | 155 +++++++++++++ .../web/demos_of_open_web_technologies/index.html | 155 ------------- files/zh-tw/_redirects.txt | 1 + files/zh-tw/_wikihistory.json | 2 +- files/zh-tw/web/demos/index.html | 145 ++++++++++++ .../web/demos_of_open_web_technologies/index.html | 144 ------------ 28 files changed, 1192 insertions(+), 1180 deletions(-) create mode 100644 files/de/web/demos/index.html delete mode 100644 files/de/web/demos_of_open_web_technologies/index.html create mode 100644 files/es/web/demos/index.html delete mode 100644 files/es/web/demos_of_open_web_technologies/index.html create mode 100644 files/fr/web/demos/index.html delete mode 100644 files/fr/web/demos_of_open_web_technologies/index.html create mode 100644 files/ja/web/demos/index.html delete mode 100644 files/ja/web/demos_of_open_web_technologies/index.html create mode 100644 files/pt-br/web/demos/index.html delete mode 100644 files/pt-br/web/demos_of_open_web_technologies/index.html create mode 100644 files/zh-cn/web/demos/index.html delete mode 100644 files/zh-cn/web/demos_of_open_web_technologies/index.html create mode 100644 files/zh-tw/web/demos/index.html delete mode 100644 files/zh-tw/web/demos_of_open_web_technologies/index.html (limited to 'files/es/_wikihistory.json') diff --git a/files/de/_redirects.txt b/files/de/_redirects.txt index 1e1a223b58..30ab6fb6ff 100644 --- a/files/de/_redirects.txt +++ b/files/de/_redirects.txt @@ -544,6 +544,7 @@ /de/docs/Web/CSS/url /de/docs/Web/CSS/url() /de/docs/Web/CSS/visible /de/docs/Web/CSS/visibility /de/docs/Web/CSS/word-wrap /de/docs/Web/CSS/overflow-wrap +/de/docs/Web/Demos_of_open_web_technologies /de/docs/Web/Demos /de/docs/Web/Events/DOMContentLoaded /de/docs/Web/API/Window/DOMContentLoaded_event /de/docs/Web/Events/change /de/docs/Web/API/HTMLElement/change_event /de/docs/Web/Events/fullscreenchange /de/docs/Web/API/Document/fullscreenchange_event diff --git a/files/de/_wikihistory.json b/files/de/_wikihistory.json index 6c44b44041..a402e431bf 100644 --- a/files/de/_wikihistory.json +++ b/files/de/_wikihistory.json @@ -7591,7 +7591,7 @@ "axlwaii" ] }, - "Web/Demos_of_open_web_technologies": { + "Web/Demos": { "modified": "2019-03-23T22:39:34.270Z", "contributors": [ "sigoa", diff --git a/files/de/web/demos/index.html b/files/de/web/demos/index.html new file mode 100644 index 0000000000..22d8922369 --- /dev/null +++ b/files/de/web/demos/index.html @@ -0,0 +1,155 @@ +--- +title: Demos für Open Web Technologie +slug: Web/Demos +tags: + - Apps + - Demos + - Example + - Translation +translation_of: Web/Demos_of_open_web_technologies +original_slug: Web/Demos_of_open_web_technologies +--- +

Mozilla unterstützt eine Vielzahl an Open Web Technologien und ermutigt ihre Verwendung, deswegen auch die ganzen toten links hier auf dieser Seite. Diese Seite bietet Links zu spannenden Demonstrationen dieser Technologien, unter anderem beliebte Demos aus dem Demo Studio, welches kürzlich geschlossen wurde. Wenn Sie eine gute Demonstration oder Anwendung von Open Web Technologie kennen, bitte fügen Sie einen Link in der passenden Sektion ein.

+ +

 

+ +

2D Grafik

+ +

APNG

+ + + +

Canvas

+ + + +

SVG

+ + + +

Video

+ + + +

3D Grafik

+ +

WebGL

+ + + +

Virtual Reality

+ + + +

CSS

+ + + +

Transformations

+ + + +

Spiele

+ + + +

HTML

+ + + +

Web APIs

+ +
    +
+ +

Notifications API

+ + + +
    +
+ +

Web Audio API

+ + + +

Web Workers

+ + diff --git a/files/de/web/demos_of_open_web_technologies/index.html b/files/de/web/demos_of_open_web_technologies/index.html deleted file mode 100644 index fffa5e1530..0000000000 --- a/files/de/web/demos_of_open_web_technologies/index.html +++ /dev/null @@ -1,154 +0,0 @@ ---- -title: Demos für Open Web Technologie -slug: Web/Demos_of_open_web_technologies -tags: - - Apps - - Demos - - Example - - Translation -translation_of: Web/Demos_of_open_web_technologies ---- -

Mozilla unterstützt eine Vielzahl an Open Web Technologien und ermutigt ihre Verwendung, deswegen auch die ganzen toten links hier auf dieser Seite. Diese Seite bietet Links zu spannenden Demonstrationen dieser Technologien, unter anderem beliebte Demos aus dem Demo Studio, welches kürzlich geschlossen wurde. Wenn Sie eine gute Demonstration oder Anwendung von Open Web Technologie kennen, bitte fügen Sie einen Link in der passenden Sektion ein.

- -

 

- -

2D Grafik

- -

APNG

- - - -

Canvas

- - - -

SVG

- - - -

Video

- - - -

3D Grafik

- -

WebGL

- - - -

Virtual Reality

- - - -

CSS

- - - -

Transformations

- - - -

Spiele

- - - -

HTML

- - - -

Web APIs

- -
    -
- -

Notifications API

- - - -
    -
- -

Web Audio API

- - - -

Web Workers

- - diff --git a/files/es/_redirects.txt b/files/es/_redirects.txt index 144e880d55..a9ca29c7e8 100644 --- a/files/es/_redirects.txt +++ b/files/es/_redirects.txt @@ -1718,6 +1718,7 @@ /es/docs/Web/CSS/transform-function/translateY /es/docs/Web/CSS/transform-function/translateY() /es/docs/Web/CSS/transform-function/translateZ /es/docs/Web/CSS/transform-function/translateZ() /es/docs/Web/CSS/var /es/docs/Web/CSS/var() +/es/docs/Web/Demos_of_open_web_technologies /es/docs/Web/Demos /es/docs/Web/Events/animationend /es/docs/Web/API/HTMLElement/animationend_event /es/docs/Web/Events/beforeunload /es/docs/Web/API/Window/beforeunload_event /es/docs/Web/Events/blur /es/docs/Web/API/Element/blur_event diff --git a/files/es/_wikihistory.json b/files/es/_wikihistory.json index be405acc83..fd2d790297 100644 --- a/files/es/_wikihistory.json +++ b/files/es/_wikihistory.json @@ -13287,7 +13287,7 @@ "pekechis" ] }, - "Web/Demos_of_open_web_technologies": { + "Web/Demos": { "modified": "2019-03-23T22:33:45.097Z", "contributors": [ "SoftwareRVG", diff --git a/files/es/web/demos/index.html b/files/es/web/demos/index.html new file mode 100644 index 0000000000..a7cf5325ce --- /dev/null +++ b/files/es/web/demos/index.html @@ -0,0 +1,162 @@ +--- +title: Demostraciones de tecnologías de Web Abierta +slug: Web/Demos +tags: + - 2D + - 3D + - CSS + - Canvas + - Design + - HTML + - SVG + - Video + - transform +translation_of: Web/Demos_of_open_web_technologies +original_slug: Web/Demos_of_open_web_technologies +--- +

Mozilla soporta una amplia variedad de emocionantes tecnologías web abiertas, y alentamos su utilización.  Esta página ofrece enlaces a interesantes demostraciones de estas tecnologías, incluyendo algunas que fueron populares en la Demo Studio, la cual ha sido retirada desde entonces. Si conoces una buena demostración o aplicación de tecnología web abierta, por favor agrega el enlace a la sección apropiada aquí.

+ +

Gráficos 2D

+ +

APNG

+ + + +

Canvas

+ + + +

SVG

+ + + +

Video

+ + + +

Gráficos 3D

+ +

WebGL

+ + + +

Realidad VIrtual

+ + + +

CSS

+ + + +

Transformaciones

+ + + +

Juegos

+ + + +

HTML

+ + + +

Web APIs

+ +
    +
+ +

 API Notificaciones

+ + + +
    +
+ +

API Web Audio

+ + + +

Funciones Web

+ + diff --git a/files/es/web/demos_of_open_web_technologies/index.html b/files/es/web/demos_of_open_web_technologies/index.html deleted file mode 100644 index 27e6816192..0000000000 --- a/files/es/web/demos_of_open_web_technologies/index.html +++ /dev/null @@ -1,161 +0,0 @@ ---- -title: Demostraciones de tecnologías de Web Abierta -slug: Web/Demos_of_open_web_technologies -tags: - - 2D - - 3D - - CSS - - Canvas - - Design - - HTML - - SVG - - Video - - transform -translation_of: Web/Demos_of_open_web_technologies ---- -

Mozilla soporta una amplia variedad de emocionantes tecnologías web abiertas, y alentamos su utilización.  Esta página ofrece enlaces a interesantes demostraciones de estas tecnologías, incluyendo algunas que fueron populares en la Demo Studio, la cual ha sido retirada desde entonces. Si conoces una buena demostración o aplicación de tecnología web abierta, por favor agrega el enlace a la sección apropiada aquí.

- -

Gráficos 2D

- -

APNG

- - - -

Canvas

- - - -

SVG

- - - -

Video

- - - -

Gráficos 3D

- -

WebGL

- - - -

Realidad VIrtual

- - - -

CSS

- - - -

Transformaciones

- - - -

Juegos

- - - -

HTML

- - - -

Web APIs

- -
    -
- -

 API Notificaciones

- - - -
    -
- -

API Web Audio

- - - -

Funciones Web

- - diff --git a/files/fr/_redirects.txt b/files/fr/_redirects.txt index 2e6bf4cbba..9cd2fc2d36 100644 --- a/files/fr/_redirects.txt +++ b/files/fr/_redirects.txt @@ -4265,7 +4265,8 @@ /fr/docs/Web/CSS/visible /fr/docs/Web/CSS/visibility /fr/docs/Web/CSS/word-wrap /fr/docs/Web/CSS/overflow-wrap /fr/docs/Web/CSS/Élément_remplacé /fr/docs/Web/CSS/Replaced_element -/fr/docs/Web/Démos_de_technologies_open_web /fr/docs/Web/Demos_of_open_web_technologies +/fr/docs/Web/Demos_of_open_web_technologies /fr/docs/Web/Demos +/fr/docs/Web/Démos_de_technologies_open_web /fr/docs/Web/Demos /fr/docs/Web/Events/DOMContentLoaded /fr/docs/Web/API/Window/DOMContentLoaded_event /fr/docs/Web/Events/abort /fr/docs/conflicting/Web/API/HTMLMediaElement/abort_event /fr/docs/Web/Events/abort_(ProgressEvent) /fr/docs/Web/API/XMLHttpRequest/abort_event diff --git a/files/fr/_wikihistory.json b/files/fr/_wikihistory.json index 121a997e06..fcdcc1acd9 100644 --- a/files/fr/_wikihistory.json +++ b/files/fr/_wikihistory.json @@ -30099,7 +30099,7 @@ "JayPanoz" ] }, - "Web/Demos_of_open_web_technologies": { + "Web/Demos": { "modified": "2019-03-18T20:44:11.081Z", "contributors": [ "goofy_mdn", diff --git a/files/fr/web/demos/index.html b/files/fr/web/demos/index.html new file mode 100644 index 0000000000..0b2ebd98a5 --- /dev/null +++ b/files/fr/web/demos/index.html @@ -0,0 +1,169 @@ +--- +title: Démos de technologies open web +slug: Web/Demos +translation_of: Web/Demos_of_open_web_technologies +original_slug: Web/Demos_of_open_web_technologies +--- +

Mozilla supporte une large gamme de technologies open web vraiment intéressantes, et nous encourageons leur utilisation. Cette page offre des liens vers d'intéressantes démonstrations de ces technologies. Si vous avez entendu parler d'une bonne démonstration ou d'une application de technologie open web, veuillez ajouter un lien vers la section appropriée ici.

+ +

Graphiques 2D

+ +

APNG

+ + + +

Canvas

+ + + +

SVG

+ + + +

Vidéos

+ + + +

Graphiques 3D

+ +

WebGL

+ + + +

Réalité Virtuelle

+ + + +

Réalité augmentée

+ + + +

CSS

+ + + +

Transformations

+ + + +

Jeux

+ + + +

HTML

+ + + +

APIs Web

+ +
    +
+ +

API de Notifications

+ + + +
    +
+ +

API Web Audio

+ + + +

API de Fichier

+ + + +

Ouvriers du Web

+ + diff --git a/files/fr/web/demos_of_open_web_technologies/index.html b/files/fr/web/demos_of_open_web_technologies/index.html deleted file mode 100644 index 6b83bdd950..0000000000 --- a/files/fr/web/demos_of_open_web_technologies/index.html +++ /dev/null @@ -1,169 +0,0 @@ ---- -title: Démos de technologies open web -slug: Web/Demos_of_open_web_technologies -translation_of: Web/Demos_of_open_web_technologies -original_slug: Web/Démos_de_technologies_open_web ---- -

Mozilla supporte une large gamme de technologies open web vraiment intéressantes, et nous encourageons leur utilisation. Cette page offre des liens vers d'intéressantes démonstrations de ces technologies. Si vous avez entendu parler d'une bonne démonstration ou d'une application de technologie open web, veuillez ajouter un lien vers la section appropriée ici.

- -

Graphiques 2D

- -

APNG

- - - -

Canvas

- - - -

SVG

- - - -

Vidéos

- - - -

Graphiques 3D

- -

WebGL

- - - -

Réalité Virtuelle

- - - -

Réalité augmentée

- - - -

CSS

- - - -

Transformations

- - - -

Jeux

- - - -

HTML

- - - -

APIs Web

- -
    -
- -

API de Notifications

- - - -
    -
- -

API Web Audio

- - - -

API de Fichier

- - - -

Ouvriers du Web

- - diff --git a/files/ja/_redirects.txt b/files/ja/_redirects.txt index de680f387d..8014f04141 100644 --- a/files/ja/_redirects.txt +++ b/files/ja/_redirects.txt @@ -3795,6 +3795,7 @@ /ja/docs/Web/Compatibility_FAQ/Tips_Default_Style_Difference.html /ja/docs/orphaned/Web/Compatibility_FAQ/Tips_Default_Style_Difference.html /ja/docs/Web/Compatibility_FAQ/Tips_Vendor_Prefix.html /ja/docs/orphaned/Web/Compatibility_FAQ/Tips_Vendor_Prefix.html /ja/docs/Web/Compatibility_FAQ/Underline_Color_Diffrence.html /ja/docs/orphaned/Web/Compatibility_FAQ/Underline_Color_Diffrence.html +/ja/docs/Web/Demos_of_open_web_technologies /ja/docs/Web/Demos /ja/docs/Web/Events/Activate /ja/docs/Web/API/Element/DOMActivate_event /ja/docs/Web/Events/DOMContentLoaded /ja/docs/Web/API/Window/DOMContentLoaded_event /ja/docs/Web/Events/abort /ja/docs/Web/API/HTMLMediaElement/abort_event diff --git a/files/ja/_wikihistory.json b/files/ja/_wikihistory.json index 44f4c575d1..db3e031f5d 100644 --- a/files/ja/_wikihistory.json +++ b/files/ja/_wikihistory.json @@ -33360,7 +33360,7 @@ "mpcjazz" ] }, - "Web/Demos_of_open_web_technologies": { + "Web/Demos": { "modified": "2019-03-23T22:34:52.877Z", "contributors": [ "dskmori" diff --git a/files/ja/web/demos/index.html b/files/ja/web/demos/index.html new file mode 100644 index 0000000000..c6feeaeeee --- /dev/null +++ b/files/ja/web/demos/index.html @@ -0,0 +1,148 @@ +--- +title: オープン Web テクノロジーのデモ +slug: Web/Demos +translation_of: Web/Demos_of_open_web_technologies +original_slug: Web/Demos_of_open_web_technologies +--- +

Mozilla は、幅広い既存の Web テクノロジーをサポートし、それらを使用することを奨励しています。このページは、かつて Demo Studio で人気のあったものも含め、技術のデモンストレーションを提供します。オープン Web テクノロジーのデモンストレーションやアプリケーションを知っている場合、適切なセクションにリンクを追加してください。

+ +

2D Graphics

+ +

APNG

+ +
    +
  • Justin's demo (ローカルに保存すると動作します)
  • +
+ +

Canvas

+ + + +

SVG

+ + + +

Video

+ + + +

3D Graphics

+ +

WebGL

+ + + +

Virtual Reality

+ + + +

CSS

+ + + +

Transformations

+ + + +

Games

+ + + +

HTML

+ + + +

Web APIs

+ +
    +
+ +

Notifications API

+ + + +
    +
+ +

Web Audio API

+ + + +

Web Workers

+ + diff --git a/files/ja/web/demos_of_open_web_technologies/index.html b/files/ja/web/demos_of_open_web_technologies/index.html deleted file mode 100644 index d41643d7b4..0000000000 --- a/files/ja/web/demos_of_open_web_technologies/index.html +++ /dev/null @@ -1,147 +0,0 @@ ---- -title: オープン Web テクノロジーのデモ -slug: Web/Demos_of_open_web_technologies -translation_of: Web/Demos_of_open_web_technologies ---- -

Mozilla は、幅広い既存の Web テクノロジーをサポートし、それらを使用することを奨励しています。このページは、かつて Demo Studio で人気のあったものも含め、技術のデモンストレーションを提供します。オープン Web テクノロジーのデモンストレーションやアプリケーションを知っている場合、適切なセクションにリンクを追加してください。

- -

2D Graphics

- -

APNG

- -
    -
  • Justin's demo (ローカルに保存すると動作します)
  • -
- -

Canvas

- - - -

SVG

- - - -

Video

- - - -

3D Graphics

- -

WebGL

- - - -

Virtual Reality

- - - -

CSS

- - - -

Transformations

- - - -

Games

- - - -

HTML

- - - -

Web APIs

- -
    -
- -

Notifications API

- - - -
    -
- -

Web Audio API

- - - -

Web Workers

- - diff --git a/files/pt-br/_redirects.txt b/files/pt-br/_redirects.txt index c8c1a6bb45..8b616cd018 100644 --- a/files/pt-br/_redirects.txt +++ b/files/pt-br/_redirects.txt @@ -623,6 +623,7 @@ /pt-BR/docs/Web/CSS/valor_inicial /pt-BR/docs/Web/CSS/initial_value /pt-BR/docs/Web/CSS/var /pt-BR/docs/Web/CSS/var() /pt-BR/docs/Web/CSS/word-wrap /pt-BR/docs/Web/CSS/overflow-wrap +/pt-BR/docs/Web/Demos_of_open_web_technologies /pt-BR/docs/Web/Demos /pt-BR/docs/Web/Events/DOMContentLoaded /pt-BR/docs/Web/API/Window/DOMContentLoaded_event /pt-BR/docs/Web/Events/abort /pt-BR/docs/Web/API/HTMLMediaElement/abort_event /pt-BR/docs/Web/Events/beforeunload /pt-BR/docs/Web/API/Window/beforeunload_event diff --git a/files/pt-br/_wikihistory.json b/files/pt-br/_wikihistory.json index d9f57768b3..0df24fcd5d 100644 --- a/files/pt-br/_wikihistory.json +++ b/files/pt-br/_wikihistory.json @@ -8930,7 +8930,7 @@ "jessuircleydson" ] }, - "Web/Demos_of_open_web_technologies": { + "Web/Demos": { "modified": "2020-09-04T06:28:02.627Z", "contributors": [ "gustavoSoriano", diff --git a/files/pt-br/web/demos/index.html b/files/pt-br/web/demos/index.html new file mode 100644 index 0000000000..509f06fd23 --- /dev/null +++ b/files/pt-br/web/demos/index.html @@ -0,0 +1,242 @@ +--- +title: Demonstrações de tecnologia web aberta +slug: Web/Demos +translation_of: Web/Demos_of_open_web_technologies +original_slug: Web/Demos_of_open_web_technologies +--- +

A mozilla suporta uma grande variedade de tecnologias abertas da web aberta e nós encorajamos seu uso.Esta página oferece links para demonstrações interessantes dessas tecnologia.

+ +

Se você conhece uma boa demonstração ou aplicação da tecnologia web aberta, adicione um link para a seção apropriada aqui.

+ +

Gráficos 2D

+ +

Tela de pintura

+ + + +

SVG

+ + + +

Vídeo

+ + + +

Gráficos 3D

+ +

WebGL

+ + + +

Realidade virtual

+ + + +

CSS

+ + + +

Transformações

+ + + +

jogos

+ + + +

HTML

+ + + +

API da Web

+ +
    +
+ +

API de notificações

+ + + +
    +
+ +

API de áudio da Web

+ + + +

API de arquivos

+ + + +

Trabalhadores da Web

+ + diff --git a/files/pt-br/web/demos_of_open_web_technologies/index.html b/files/pt-br/web/demos_of_open_web_technologies/index.html deleted file mode 100644 index 3fd3092c8f..0000000000 --- a/files/pt-br/web/demos_of_open_web_technologies/index.html +++ /dev/null @@ -1,241 +0,0 @@ ---- -title: Demonstrações de tecnologia web aberta -slug: Web/Demos_of_open_web_technologies -translation_of: Web/Demos_of_open_web_technologies ---- -

A mozilla suporta uma grande variedade de tecnologias abertas da web aberta e nós encorajamos seu uso.Esta página oferece links para demonstrações interessantes dessas tecnologia.

- -

Se você conhece uma boa demonstração ou aplicação da tecnologia web aberta, adicione um link para a seção apropriada aqui.

- -

Gráficos 2D

- -

Tela de pintura

- - - -

SVG

- - - -

Vídeo

- - - -

Gráficos 3D

- -

WebGL

- - - -

Realidade virtual

- - - -

CSS

- - - -

Transformações

- - - -

jogos

- - - -

HTML

- - - -

API da Web

- -
    -
- -

API de notificações

- - - -
    -
- -

API de áudio da Web

- - - -

API de arquivos

- - - -

Trabalhadores da Web

- - diff --git a/files/zh-cn/_redirects.txt b/files/zh-cn/_redirects.txt index c9a3dcc7c3..ff820f35f0 100644 --- a/files/zh-cn/_redirects.txt +++ b/files/zh-cn/_redirects.txt @@ -1776,6 +1776,7 @@ /zh-CN/docs/Web/CSS/文本装饰线厚度(粗细) /zh-CN/docs/Web/CSS/text-decoration-thickness /zh-CN/docs/Web/CSS/混合模式 /zh-CN/docs/Web/CSS/blend-mode /zh-CN/docs/Web/CSS/网格-模板-列 /zh-CN/docs/Web/CSS/grid-template-rows +/zh-CN/docs/Web/Demos_of_open_web_technologies /zh-CN/docs/Web/Demos /zh-CN/docs/Web/Events/Activate /zh-CN/docs/Web/API/Element/DOMActivate_event /zh-CN/docs/Web/Events/DOMContentLoaded /zh-CN/docs/Web/API/Window/DOMContentLoaded_event /zh-CN/docs/Web/Events/DOMContentLoaded_(event) /zh-CN/docs/Web/API/Window/DOMContentLoaded_event @@ -2187,7 +2188,7 @@ /zh-CN/docs/Web/媒体 /zh-CN/docs/Web/Media /zh-CN/docs/Web/媒体/Autoplay_guide /zh-CN/docs/Web/Media/Autoplay_guide /zh-CN/docs/Web/性能 /zh-CN/docs/Web/Performance -/zh-CN/docs/Web/演示说明 /zh-CN/docs/Web/Demos_of_open_web_technologies +/zh-CN/docs/Web/演示说明 /zh-CN/docs/Web/Demos /zh-CN/docs/WebAPI/Using_geolocation /zh-CN/docs/Web/API/Geolocation_API /zh-CN/docs/WebAssembly/概念 /zh-CN/docs/WebAssembly/Concepts /zh-CN/docs/WebGL /zh-CN/docs/Web/API/WebGL_API diff --git a/files/zh-cn/_wikihistory.json b/files/zh-cn/_wikihistory.json index 3e599cf40f..ea8dba13d9 100644 --- a/files/zh-cn/_wikihistory.json +++ b/files/zh-cn/_wikihistory.json @@ -30794,7 +30794,7 @@ "TimZhao" ] }, - "Web/Demos_of_open_web_technologies": { + "Web/Demos": { "modified": "2019-09-04T03:32:34.828Z", "contributors": [ "RainSlide", diff --git a/files/zh-cn/web/demos/index.html b/files/zh-cn/web/demos/index.html new file mode 100644 index 0000000000..04c11c2257 --- /dev/null +++ b/files/zh-cn/web/demos/index.html @@ -0,0 +1,155 @@ +--- +title: 开源 Web 技术示例 +slug: Web/Demos +tags: + - 2D + - 3D + - CSS + - Canvas + - Design + - HTML + - SVG + - Video +translation_of: Web/Demos_of_open_web_technologies +original_slug: Web/Demos_of_open_web_technologies +--- +

Mozilla 支持各种令人兴奋的开源 Web 技术,我们鼓励大家使用它们。此页面提供了有关这些技术的一些有趣演示链接。

+ +

如果你知道开源 Web 技术的优秀演示或者应用,就在这里(以及 英文页面)添加一个合适的链接吧。

+ +

2D 图形

+ +

Canvas

+ + + +

SVG

+ + + +

视频

+ + + +

3D 图像

+ +

WebGL

+ + + +

虚拟现实(VR)

+ + + +

CSS

+ + + +

旧项目:

+ + + +

变换

+ + + +

游戏

+ + + +

Web API

+ +
    +
+ +

通知 API

+ + + +
    +
+ +

网络音频 API

+ + + +

文件 API

+ + + +

其他

+ + diff --git a/files/zh-cn/web/demos_of_open_web_technologies/index.html b/files/zh-cn/web/demos_of_open_web_technologies/index.html deleted file mode 100644 index 29978d4ed2..0000000000 --- a/files/zh-cn/web/demos_of_open_web_technologies/index.html +++ /dev/null @@ -1,155 +0,0 @@ ---- -title: 开源 Web 技术示例 -slug: Web/Demos_of_open_web_technologies -tags: - - 2D - - 3D - - CSS - - Canvas - - Design - - HTML - - SVG - - Video -translation_of: Web/Demos_of_open_web_technologies -original_slug: Web/演示说明 ---- -

Mozilla 支持各种令人兴奋的开源 Web 技术,我们鼓励大家使用它们。此页面提供了有关这些技术的一些有趣演示链接。

- -

如果你知道开源 Web 技术的优秀演示或者应用,就在这里(以及 英文页面)添加一个合适的链接吧。

- -

2D 图形

- -

Canvas

- - - -

SVG

- - - -

视频

- - - -

3D 图像

- -

WebGL

- - - -

虚拟现实(VR)

- - - -

CSS

- - - -

旧项目:

- - - -

变换

- - - -

游戏

- - - -

Web API

- -
    -
- -

通知 API

- - - -
    -
- -

网络音频 API

- - - -

文件 API

- - - -

其他

- - diff --git a/files/zh-tw/_redirects.txt b/files/zh-tw/_redirects.txt index 079c3da530..ba04b91d36 100644 --- a/files/zh-tw/_redirects.txt +++ b/files/zh-tw/_redirects.txt @@ -598,6 +598,7 @@ /zh-TW/docs/Web/CSS/彈頭 /zh-TW/docs/Web/CSS/box-sizing /zh-TW/docs/Web/CSS/繼承 /zh-TW/docs/Web/CSS/inheritance /zh-TW/docs/Web/CSS/語法 /zh-TW/docs/Web/CSS/Syntax +/zh-TW/docs/Web/Demos_of_open_web_technologies /zh-TW/docs/Web/Demos /zh-TW/docs/Web/Events/DOMContentLoaded /zh-TW/docs/Web/API/Window/DOMContentLoaded_event /zh-TW/docs/Web/Events/abort /zh-TW/docs/Web/API/HTMLMediaElement/abort_event /zh-TW/docs/Web/Events/click /zh-TW/docs/Web/API/Element/click_event diff --git a/files/zh-tw/_wikihistory.json b/files/zh-tw/_wikihistory.json index a3732164fe..bbfdfa477f 100644 --- a/files/zh-tw/_wikihistory.json +++ b/files/zh-tw/_wikihistory.json @@ -5382,7 +5382,7 @@ "yutzuch" ] }, - "Web/Demos_of_open_web_technologies": { + "Web/Demos": { "modified": "2019-03-23T22:08:13.863Z", "contributors": [ "h223449961", diff --git a/files/zh-tw/web/demos/index.html b/files/zh-tw/web/demos/index.html new file mode 100644 index 0000000000..862fc1bbbb --- /dev/null +++ b/files/zh-tw/web/demos/index.html @@ -0,0 +1,145 @@ +--- +title: Demos of open web technologies +slug: Web/Demos +tags: + - 影片 + - 網站 + - 網頁 + - 設計 +translation_of: Web/Demos_of_open_web_technologies +original_slug: Web/Demos_of_open_web_technologies +--- +

Mozilla 支援豐富、廣泛且扣人心弦的網路公開技術,並且我們鼓勵使用他們。這個頁面提供一些展示這些有趣技術的連結,包含那些曾經在 Demo Studio 有人氣的,但現在已經落伍了的技術。如果你知道有關於新的網路公開技術,不錯的展示或是應用程式,請將連結加到下方適合的區塊中。

+ +

2D 繪圖

+ +

Canvas

+ + + +

SVG

+ + + +

影片

+ + + +

3D 繪圖

+ +

WebGL

+ + + +

虛擬實境 ( Virtual Reality )

+ + + +

CSS

+ + + +

轉換 ( Transformations )

+ + + +

遊戲

+ + + +

HTML

+ + + +

Web APIs

+ +
    +
+ +

提示工具的 API

+ + + +
    +
+ +

網路 API

+ + + +

檔案的 API

+ + + +

Web Workers

+ + diff --git a/files/zh-tw/web/demos_of_open_web_technologies/index.html b/files/zh-tw/web/demos_of_open_web_technologies/index.html deleted file mode 100644 index 5baa250a38..0000000000 --- a/files/zh-tw/web/demos_of_open_web_technologies/index.html +++ /dev/null @@ -1,144 +0,0 @@ ---- -title: Demos of open web technologies -slug: Web/Demos_of_open_web_technologies -tags: - - 影片 - - 網站 - - 網頁 - - 設計 -translation_of: Web/Demos_of_open_web_technologies ---- -

Mozilla 支援豐富、廣泛且扣人心弦的網路公開技術,並且我們鼓勵使用他們。這個頁面提供一些展示這些有趣技術的連結,包含那些曾經在 Demo Studio 有人氣的,但現在已經落伍了的技術。如果你知道有關於新的網路公開技術,不錯的展示或是應用程式,請將連結加到下方適合的區塊中。

- -

2D 繪圖

- -

Canvas

- - - -

SVG

- - - -

影片

- - - -

3D 繪圖

- -

WebGL

- - - -

虛擬實境 ( Virtual Reality )

- - - -

CSS

- - - -

轉換 ( Transformations )

- - - -

遊戲

- - - -

HTML

- - - -

Web APIs

- -
    -
- -

提示工具的 API

- - - -
    -
- -

網路 API

- - - -

檔案的 API

- - - -

Web Workers

- - -- cgit v1.2.3-54-g00ecf