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/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 --------- 16 files changed, 1478 insertions(+), 1466 deletions(-) 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 (limited to 'files/ru') 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")}}

+ +

Смотрите также

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

+
+ +

Смотрите также

+ + + +
+
+
+ +
+
+
+ +
+

+ +

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

где

+ + + +

Необходимо принять во внимание, что передача дополнительных параметров функции в первом варианте не работает в 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")}}

- -

Смотрите также

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

-
- -

Смотрите также

- - - -
-
-
- -
-
-
- -
-

- -

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

где

- - - -

Необходимо принять во внимание, что передача дополнительных параметров функции в первом варианте не работает в 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.

- -

Также интересно

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