aboutsummaryrefslogtreecommitdiff
path: root/files/uk/web/api/windowtimers/settimeout/index.html
blob: 19c90148ce70fd356a7a2b481cf4af3a2f904f05 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
---
title: WindowTimers.setTimeout()
slug: Web/API/WindowTimers/setTimeout
translation_of: Web/API/WindowOrWorkerGlobalScope/setTimeout
---
<div>{{APIRef("HTML DOM")}}</div>

<div> </div>

<div>Метод <code>setTimeout()</code>, що належить об'єкту {{domxref("WindowOrWorkerGlobalScope")}}, та наслідується від window.setTimeout,  встановлює таймер, що виконує функцію або вказаний фрагмент коду один раз, щойно спливе заданий час.</div>

<div> </div>

<h2 id="Синтаксис">Синтаксис</h2>

<pre class="syntaxbox"><em>var timeoutID</em> = window.setTimeout(<em>func</em>[, <em>delay</em>, <em>param1</em>, <em>param2</em>, ...]);
<em>var timeoutID</em> = window.setTimeout(<em>code</em>[, <em>delay</em>]);
</pre>

<h3 id="Параметри">Параметри</h3>

<dl>
 <dt><code>func</code></dt>
 <dd>{{jsxref("function")}} котру необхідно виконати після того, як вийде заданий час.</dd>
 <dt><code>code</code></dt>
 <dd>Опційний синтаксис, котрий дозволяє задавати рядок замість функції, котра компілюється і виконується при спрацюванні таймера. Використання цього синтаксису <strong>не рекомендовано</strong> з тих же ж причин, котрі роблять застосування {{jsxref("eval()")}} загрозою безпеці.</dd>
 <dt><code>delay</code> {{optional_inline}}</dt>
 <dt> </dt>
 <dd>Час у мілісекундах (тисячних секунди), котрий таймер має зачекати перед тим, як виконати вказану функцію або код. Якщо цей параметр пропустити, буде використано значення 0. Варто зазначити, що справжній час затримки, може бути довшим. Дивіться розділ {{anch("Reasons for delays longer than specified","Причини, з яких затримка є фактично довшою ніж задано")}}</dd>
 <dt><code>param1, ..., paramN</code> {{optional_inline}}</dt>
 <dd>Додаткові параметри, що передаються до <em>func </em>або <em>code</em>, щойно час таймера спливе.</dd>
</dl>

<div class="note">
<p><strong>Зверніть увагу: </strong> Internet Explorer 9 та більш ранні версії не підтримують додаткові параметри. Застосовуйте поліфіл, щобл уможливити цей функціонал (див. розділ <a href="#Callback_arguments">Callback arguments</a>).  </p>
</div>

<h3 id="Значення_що_повертається">Значення, що повертається</h3>

<p><br>
 Після виклику <code>setTimeout()</code>, повертається <code>timeoutID</code>  - це не нульове цифрове значення, що використовується для ідентифікації створеного таймера. Цей ідентифікатор можна передати як параметр до {{domxref("Window.clearTimeout()")}} щоб відмінити таймер.</p>

<p>Корисно знати, що <code>setTimeout()</code> та {{domxref("WindowTimers.setInterval", "setInterval()")}} використовують спільну колекцію ID ідентифікаторів, а також що  <code>clearTimeout()</code> та {{domxref("WindowTimers.clearInterval", "clearInterval()")}} технічно можуть бути взаємозамінними. Тим не менше, задля ясності, варто завжди зіставляти їх, аби не допускати помилок під час розробки коду. </p>

<h2 id="Приклад">Приклад</h2>

<p>У наступному прикладі створено дві кнопки на веб сторінці, що прив'язані до <code>setTimeout()</code> та <code>clearTimeout()</code> процесів. Після натискання на першу кнопку встановлюється таймер, що викликає діалогове вікно alert через дві секунди та зберігає ID таймера для подальшого використання у <code>clearTimeout()</code>. За бажанням ви можете відмінити цей таймер, якщо натисните другу кнопку.</p>

<h3 id="HTML_код">HTML код</h3>

<pre class="brush: html">&lt;p&gt;Live Example&lt;/p&gt;
&lt;button onclick="delayedAlert();"&gt;Відобразити діалогове вікно alert через дві секунди.&lt;/button&gt;
&lt;p&gt;&lt;/p&gt;
&lt;button onclick="clearAlert();"&gt;Відмінити відображення діалогового вікна.&lt;/button&gt;
</pre>

<h3 id="JavaScript_код">JavaScript код</h3>

<pre class="brush: js">var timeoutID;

function delayedAlert() {
  timeoutID = window.setTimeout(slowAlert, 2000);
}

function slowAlert() {
  alert("Це було дійсно повільно!");
}

function clearAlert() {
  window.clearTimeout(timeoutID);
}
</pre>

<h3 id="Результат">Результат</h3>

<p>{{EmbedLiveSample('Example', 'Приклад')}}</p>

<p>Дивіться також <a href="/en-US/docs/Web/API/WindowTimers/clearTimeout#Example"><code>clearTimeout()</code> example</a>.</p>

<h2 id="Поліфіл">Поліфіл</h2>

<p>Якщо вам необхідно передати один чи декілька аргументів до колбек функції, а також потрібно, щоб цей функціонал працював у браузерах, що не підтримують передачу додаткових аргументів для <code>setTimeout()</code> чи <code>setInterval()</code> (наприклад, версії Internet Explorer 9 чи нижче), ви можете застосувати цей поліфіл, який активує стандартну HTML5 функціональність. Просто додайте цей код на початку вашого скрипта: </p>

<pre class="brush: js">/*\
|*|
|*|  Polyfill which enables the passage of arbitrary arguments to the
|*|  callback functions of JavaScript timers (HTML5 standard syntax).
|*|
|*|  https://developer.mozilla.org/en-US/docs/DOM/window.setInterval
|*|
|*|  Syntax:
|*|  var timeoutID = window.setTimeout(func, delay[, param1, param2, ...]);
|*|  var timeoutID = window.setTimeout(code, delay);
|*|  var intervalID = window.setInterval(func, delay[, param1, param2, ...]);
|*|  var intervalID = window.setInterval(code, delay);
|*|
\*/

(function() {
  setTimeout(function(arg1) {
    if (arg1 === 'test') {
      // feature test is passed, no need for polyfill
      return;
    }
    var __nativeST__ = window.setTimeout;
    window.setTimeout = function(vCallback, nDelay /*, argumentToPass1, argumentToPass2, etc. */ ) {
      var aArgs = Array.prototype.slice.call(arguments, 2);
      return __nativeST__(vCallback instanceof Function ? function() {
        vCallback.apply(null, aArgs);
      } : vCallback, nDelay);
    };
  }, 0, 'test');

  var interval = setInterval(function(arg1) {
    clearInterval(interval);
    if (arg1 === 'test') {
      // feature test is passed, no need for polyfill
      return;
    }
    var __nativeSI__ = window.setInterval;
    window.setInterval = function(vCallback, nDelay /*, argumentToPass1, argumentToPass2, etc. */ ) {
      var aArgs = Array.prototype.slice.call(arguments, 2);
      return __nativeSI__(vCallback instanceof Function ? function() {
        vCallback.apply(null, aArgs);
      } : vCallback, nDelay);
    };
  }, 0, 'test');
}())
</pre>

<h2 id="Фікс_для_IE">Фікс для IE</h2>

<p>Якщо вам потрібен фікс, який не впливатиме на роботу жодного іншого мобільного чи десктопного браузера, окрім IE9 та нижче, ви можете скористатись умовними коментарями JavaScript:</p>

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

<p>Або використати умовні коментарі HTML для IE9 та нижче:</p>

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

<h2 id="Тимчасові_рішення">Тимчасові рішення</h2>

<p>Ще одне можливе рішення - використання анонімної функції для виклику колбека, але це вартісне рішення. Приклад:</p>

<pre class="brush: js">var intervalID = setTimeout(function() { myFunc("one", "two", "three"); }, 1000);
</pre>

<p>Приклад, наведений вище, може бути також написаний за допомогою   <a href="/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions">arrow function</a>:</p>

<pre class="brush: js">var intervalID = setTimeout(() =&gt; { myFunc("one", "two", "three"); }, 1000);
</pre>

<p>Ще одне рішення - використання   <a href="/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/bind">function's <code>bind</code></a>. Приклад:</p>

<pre class="brush: js">setTimeout(function(arg1){}.bind(undefined, 10), 1000);
</pre>

<h2 id="Проблема_this">Проблема "<code>this</code>"</h2>

<p>Коли ви передаєте до <code>setTimeout()</code> метод або будь-яку іншу функцію, ймовірно вона буде викликана не з тим значенням <code>this</code>, на яке ви очікуєте. Ця проблема детально описана у <a href="/en-US/docs/Web/JavaScript/Reference/Operators/this#As_an_object_method">JavaScript reference</a>.</p>

<h3 id="Пояснення">Пояснення</h3>

<p>Код, що виконується всередині <code>setTimeout()</code>, викликається із  іншого контекста виконання (<em>execution context</em>), ніж у функції, яка викликала <code>setTimeout</code>. До функції, яку викликають всередині <code>setTimeout</code> застосовуються звичайні правила призначення <code>this</code>. І, якщо ви не встановили <code>this</code> під час виклику або за допомогою <code>bind</code>, його значенням за замовчуванням буде об'єкт  <code>global</code> (або <code>window</code>) у нестрогому режимі, або <code>undefined</code> у строгому режимі. Значення <code>this</code> буде іншим, аніж у функції, яка викликала <code>setTimeout</code>. Розгляньте наступний приклад:</p>

<pre class="brush: js">myArray = ["zero", "one", "two"];
myArray.myMethod = function (sProperty) {
    alert(arguments.length &gt; 0 ? this[sProperty] : this);
};

myArray.myMethod(); // prints "zero,one,two"
myArray.myMethod(1); // prints "one"</pre>

<p>Приклад вище працює тому, що <code>myMethod</code> викликано, як метод масиву <code>myArray</code>. Тому його <code>this</code> дорівнює <code>myArray</code>, а значення <code>this[sProperty]</code> всередині метода дорівнює <code>myArray[sProperty]</code>. Тим не менше, у наступному прикладі:</p>

<pre class="brush: js">setTimeout(myArray.myMethod, 1000); // prints "[object Window]" after 1 second
setTimeout(myArray.myMethod, 1500, "1"); // prints "undefined" after 1.5 seconds</pre>

<p>Метод <code>myArray.myMethod</code> передано до <code>setTimeout</code>, як звичайну функцію, якій не задано значення <code>this</code>. І коли вона викликається, її <code>this</code> за замовчуванням дорівнює об'єкту <code>window</code>. У  <code>setTimeout</code> неможливо передати <code>this</code> аргументом, як, наприклад, у методи Array (forEach, reduce, тощо), або через використання  <code>call</code>, як показано у прикладі нижче:</p>

<pre class="brush: js">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
</pre>

<h3 id="Можливі_рішення">Можливі рішення</h3>

<p>Типовий спосіб вирішення цієї проблеми - використання функції обгортки, яка встановлює <code>this</code> із необхідним значенням: </p>

<pre class="brush: js">setTimeout(function(){myArray.myMethod()}, 2000); // prints "zero,one,two" after 2 seconds
setTimeout(function(){myArray.myMethod('1')}, 2500); // prints "one" after 2.5 seconds</pre>

<p>Стрілочна функція також є прийнятною альтернативою:</p>

<pre class="brush: js">setTimeout(() =&gt; {myArray.myMethod()}, 2000); // prints "zero,one,two" after 2 seconds
setTimeout(() =&gt; {myArray.myMethod('1')}, 2500); // prints "one" after 2.5 seconds</pre>

<p>Ще одне можливе рішення проблеми <code>this</code> - замінити нативні глобальні функції <code>setTimeout()</code> та <code>setInterval()</code> кастомними функціями, які можуть приймати об'єкт <code>this</code> і застосовувати його у колбек функції, використовуючи  <a href="/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/call"><code>Function.prototype.call</code></a>. Наприклад: </p>

<pre class="brush: js">// Enable setting 'this' in JavaScript timers

var __nativeST__ = window.setTimeout,
    __nativeSI__ = window.setInterval;

window.setTimeout = function (vCallback, nDelay /*, argumentToPass1, argumentToPass2, etc. */) {
  var oThis = this,
      aArgs = Array.prototype.slice.call(arguments, 2);
  return __nativeST__(vCallback instanceof Function ? function () {
    vCallback.apply(oThis, aArgs);
  } : vCallback, nDelay);
};

window.setInterval = function (vCallback, nDelay /*, argumentToPass1, argumentToPass2, etc. */) {
  var oThis = this,
      aArgs = Array.prototype.slice.call(arguments, 2);
  return __nativeSI__(vCallback instanceof Function ? function () {
    vCallback.apply(oThis, aArgs);
  } : vCallback, nDelay);
};</pre>

<div class="note"><strong>Зверніть увагу:  </strong>Подібний підхід дозволяє передавати будь-яку кількість аргументів у колбек функцію таймерів навіть для IE. Таким чином, цей спосіб може також бути використаний як поліфіл. Перегляньте параграф <a href="#Callback_arguments">Callback arguments</a> .</div>

<p>Випробування нового підхода:</p>

<pre class="brush: js">myArray = ["zero", "one", "two"];
myArray.myMethod = function (sProperty) {
    alert(arguments.length &gt; 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
</pre>

<div class="note"><strong>Зверніть увагу:  </strong>JavaScript 1.8.5 впровадив метод   <code><a href="/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/bind">Function.prototype.bind()</a></code>, який встановлює значення <code>this</code> для кожного виклику вказаної функції. Це допомагає уникнути використання функції обгортки для призначення <code>this</code> колбека.</div>

<p>Приклад використання <code>bind()</code>:</p>

<pre class="brush: js">myArray = ["zero", "one", "two"];
myBoundMethod = (function (sProperty) {
    console.log(arguments.length &gt; 0 ? this[sProperty] : this);
}).bind(myArray);

myBoundMethod(); // prints "zero,one,two" because 'this' is bound to myArray in the function
myBoundMethod(1); // prints "one"
setTimeout(myBoundMethod, 1000); // still prints "zero,one,two" after 1 second because of the binding
setTimeout(myBoundMethod, 1500, "1"); // prints "one" after 1.5 seconds
</pre>

<h2 id="Примітки">Примітки</h2>

<p>Таймер можна скасувати за допомогою {{domxref("Window.clearTimeout()")}}. Щоб викликати функцію повторно (наприклад, через кожні N мілісекунди), використовуйте  {{domxref("Window.setInterval()")}}.</p>

<p>Важливо пам'ятати, що функція або фрагмент коду не можуть бути виконані, допоки не буде завершено поток функції, яка викликала <code>setTimeout()</code>. Наприклад. </p>

<pre class="brush: js">function foo(){
  console.log('foo has been called');
}
setTimeout(foo, 0);
console.log('After setTimeout');</pre>

<p>Виведе в консоль:</p>

<pre class="brush: js">After setTimeout
foo has been called</pre>

<p>Тому що, навіть не зважаючи на те, що <code>setTimeout</code> було викликано із нульовою затримкою, вона переміщується у чергу і її виконання відбудеться у найближчому наступному циклі, тобто не відразу. Код, що в данний момент виконується, повинен бути завершений. Тільки після цього функції, переміщені в чергу, будуть виконані. Тому порядок виконання може бути іншим, аніж очікувалось.</p>

<h3 id="Passing_string_literals">Passing string literals</h3>

<p>Passing a string instead of a function to <code>setTimeout()</code> suffers from the same hazards as using <code><a href="/en-US/docs/JavaScript/Reference/Global_Objects/eval#Don.27t_use_eval.21">eval</a>. </code></p>

<pre class="brush: js">// Recommended
window.setTimeout(function() {
    alert("Hello World!");
}, 500);

// Not recommended
window.setTimeout("alert('Hello World!');", 500);
</pre>

<p>A string passed to <code>setTimeout</code> is evaluated in the global context, so local symbols in the context where <code>setTimeout()</code> was called will not be available when the string is evaluated as code.</p>

<h3 id="Причини_чому_затримка_є_фактично_довшою_ніж_вказано">Причини чому затримка є фактично довшою ніж вказано</h3>

<p>There are a number of reasons why a timeout may take longer to fire than anticipated. This section describes the most common reasons.</p>

<h4 id="Nested_timeouts_forced_to_>4ms">Nested timeouts forced to &gt;=4ms</h4>

<p><a class="external" href="http://code.google.com/p/chromium/issues/detail?id=792#c10">Historically</a> browsers implement <code>setTimeout()</code> "clamping": successive <code>setTimeout()</code> calls with <code>delay</code> smaller than the "minimum delay" limit are forced to use at least the minimum delay. The minimum delay, <code>DOM_MIN_TIMEOUT_VALUE</code>, is 4 ms (stored in a preference in Firefox: <code>dom.min_timeout_value</code>), with a <code>DOM_CLAMP_TIMEOUT_NESTING_LEVEL</code> of 5.</p>

<p>In fact, 4 ms is <a class="external" href="http://www.whatwg.org/specs/web-apps/current-work/multipage/timers.html#timers">specified by the HTML5 spec</a> 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.</p>

<p>To implement a 0 ms timeout in a modern browser, you can use {{domxref("window.postMessage()")}} as <a class="external" href="http://dbaron.org/log/20100309-faster-timeouts">described here</a>.</p>

<h4 id="Timeouts_in_inactive_tabs_clamped_to_>1000ms">Timeouts in inactive tabs clamped to &gt;=1000ms</h4>

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

<p>Firefox implements this behavior since version 5 (see {{bug(633421)}}, the 1000ms constant can be tweaked through the <span class="comment-copy"><code>dom.min_background_timeout_value</code> preference).</span> Chrome implements this behavior since version 11 (<a class="external" href="http://crbug.com/66078">crbug.com/66078</a>).</p>

<p>Firefox for Android uses a timeout value of 15 minutes for background tabs since {{bug(736602)}} in Firefox 14, and background tabs can also be unloaded entirely.</p>

<div class="note">
<p>Firefox 50 no longer throttles background tabs if a Web Audio API {{domxref("AudioContext")}} is actively playing sound. Firefox 51 further amends this such that background tabs are no longer throttled if an {{domxref("AudioContext")}} is present in the tab at all, even if no sound is being played. These resolve a number of issues with apps which play note-based music not being able to time or synchronize the music properly when the tab is in the background.</p>
</div>

<h4 id="Late_timeouts">Late timeouts</h4>

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

<h3 id="Maximum_delay_value">Maximum delay value</h3>

<p>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.</p>

<h2 id="Specifications">Specifications</h2>

<table class="standard-table">
 <tbody>
  <tr>
   <th>Specification</th>
   <th>Status</th>
   <th>Comment</th>
  </tr>
  <tr>
   <td>{{SpecName("HTML WHATWG", "webappapis.html#dom-settimeout", "WindowTimers.setTimeout()")}}</td>
   <td>{{Spec2("HTML WHATWG")}}</td>
   <td>Initial definition (DOM Level 0)</td>
  </tr>
 </tbody>
</table>

<h2 id="Browser_compatibility">Browser compatibility</h2>

<p>{{CompatibilityTable}}</p>

<div id="compat-desktop">
<table class="compat-table">
 <tbody>
  <tr>
   <th>Feature</th>
   <th>Chrome</th>
   <th>Firefox (Gecko)</th>
   <th>Internet Explorer</th>
   <th>Opera</th>
   <th>Safari</th>
  </tr>
  <tr>
   <td>Basic support</td>
   <td>1.0</td>
   <td>{{CompatGeckoDesktop("1")}}</td>
   <td>4.0</td>
   <td>4.0</td>
   <td>1.0</td>
  </tr>
  <tr>
   <td>Supports parameters for callback<sup>[1]</sup></td>
   <td>{{CompatVersionUnknown}}</td>
   <td>{{CompatVersionUnknown}}</td>
   <td>10.0</td>
   <td>{{CompatVersionUnknown}}</td>
   <td>{{CompatVersionUnknown}}</td>
  </tr>
 </tbody>
</table>
</div>

<div id="compat-mobile">
<table class="compat-table">
 <tbody>
  <tr>
   <th>Feature</th>
   <th>Android</th>
   <th>Chrome for Android</th>
   <th>Firefox Mobile (Gecko)</th>
   <th>IE Mobile</th>
   <th>Opera Mobile</th>
   <th>Safari Mobile</th>
  </tr>
  <tr>
   <td>Basic support</td>
   <td>1.0</td>
   <td>1.0</td>
   <td>{{CompatGeckoMobile("1")}}</td>
   <td>6.0</td>
   <td>6.0</td>
   <td>1.0</td>
  </tr>
  <tr>
   <td>Supports parameters for callback<sup>[1]</sup></td>
   <td>{{CompatUnknown}}</td>
   <td>{{CompatUnknown}}</td>
   <td>{{CompatUnknown}}</td>
   <td>{{CompatUnknown}}</td>
   <td>{{CompatUnknown}}</td>
   <td>{{CompatUnknown}}</td>
  </tr>
 </tbody>
</table>
</div>

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

<h2 id="See_also">See also</h2>

<ul>
 <li><a href="/en-US/Add-ons/Code_snippets/Timers">JavaScript timers</a></li>
 <li><a href="/en-US/docs/Mozilla/JavaScript_code_modules/Timer.jsm">Timer.jsm</a></li>
 <li>{{domxref("WindowTimers.setInterval")}}</li>
 <li>{{domxref("window.requestAnimationFrame")}}</li>
 <li><a href="/en-US/Add-ons/Code_snippets/Timers/Daemons"><em>Daemons</em> management</a></li>
</ul>