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
|
---
title: Using microtasks in JavaScript with queueMicrotask()
slug: Web/API/HTML_DOM_API/Microtask_guide
tags:
- API
- Batch
- Guide
- HTML DOM
- JavaScript
- Microtask
- Queue
- Reference
- ServiceWorker
- SharedWorker
- Window
- Worker
- asynchronous
- queueMicrotask
translation_of: Web/API/HTML_DOM_API/Microtask_guide
---
<p>{{APIRef("HTML DOM")}}</p>
<p><span class="seoSummary"><strong>マイクロタスク</strong> は、それを作成する関数/プログラムが終了した後、JavaScript実行スタックが空な場合のみに、スクリプトの実行環境を動かしている{{Glossary("user agent")}}が使っているイベントループに制御が戻る前に実行される短い関数です。</span>このイベントループはブラウザーのメインのイベントループと、<a href="/ja/docs/Web/API/Web_Workers_API">web worker</a>が動かしているイベントループのいずれかです。 これにより、ある関数が他のスクリプトの実行に干渉するリスクを除外して実行できます。またマイクロタスクが取ったアクションにユーザーエージェントが反応するよりも前に、マイクロタスクを確実に実行させることもできます。</p>
<p>JavaScript <a href="/ja/docs/Web/JavaScript/Reference/Global_Objects/Promise">promises</a> and the <a href="//en-US/docs/Web/API/Mutation_Observer_API">Mutation Observer API</a> both use the microtask queue to run their callbacks, but there are other times when the ability to defer work until the current event loop pass is wrapping up. In order to allow microtasks to be used by third-party libraries, frameworks, and polyfills, the {{domxref("WindowOrWorkerGlobalScope.queueMicrotask", "queueMicrotask()")}} method is exposed on the {{domxref("Window")}} and {{domxref("Worker")}} interfaces through the {{domxref("WindowOrWorkerGlobalScope")}} mixin.</p>
<h2 id="Tasks_vs_microtasks" name="Tasks_vs_microtasks">タスクとマイクロタスクの比較</h2>
<p>To properly discuss microtasks, it's first useful to know what a JavaScript task is and how microtasks differ from tasks. This is a quick, simplified explanation, but if you would like more details, you can read the information in the article <a href="/ja/docs/Web/API/HTML_DOM_API/Microtask_guide/In_depth">In depth: Microtasks and the JavaScript runtime environment</a>.</p>
<h3 id="Tasks" name="Tasks">タスク</h3>
<p>A <strong>task</strong> is any JavaScript code which is scheduled to be run by the standard mechanisms such as initially starting to run a program, an event callback being run, or an interval or timeout being fired. These all get scheduled on the <strong>task queue</strong>.</p>
<p>Tasks get added to the task queue when:</p>
<ul>
<li>A new JavaScript program or subprogram is executed (such as from a console, or by running the code in a {{HTMLElement("script")}} element) directly.</li>
<li>An event fires, adding the event's callback function to the task queue.</li>
<li>A timeout or interval created with {{domxref("WindowOrWorkerGlobalScope.setTimeout", "setTimeout()")}} or {{domxref("WindowOrWorkerGlobalScope.setInterval", "setInterval()")}} is reached, causing the corresponding callback to be added to the task queue.</li>
</ul>
<p>The event loop driving your code handles these tasks one after another, in the order in which they were enqueued. Only tasks which were <em>already in the task queue</em> when the event loop pass began will be executed during the current iteration. The rest will have to wait until the following iteration.</p>
<h3 id="Microtasks" name="Microtasks">マイクロタスク</h3>
<p>At first the difference between microtasks and tasks seems minor. And they are similar; both are made up of JavaScript code which gets placed on a queue and run at an appropriate time. However, whereas the event loop runs only the tasks present on the queue when the iteration began, one after another, it handles the microtask queue very differently.</p>
<p>There are two key differences.</p>
<p>First, each time a task exits, the event loop checks to see if the task is returning control to other JavaScript code. If not, it runs all of the microtasks in the microtask queue. The microtask queue is, then, processed multiple times per iteration of the event loop, including after handling events and other callbacks.</p>
<p>Second, if a microtask adds more microtasks to the queue by calling {{domxref("WindowOrWorkerGlobalScope.queueMicrotask", "queueMicrotask()")}}, those newly-added microtasks <em>execute before the next task is run</em>. That's because the event loop will keep calling microtasks until there are none left in the queue, even if more keep getting added.</p>
<div class="blockIndicator warning">
<p><strong>Warning:</strong> Since microtasks can themselves enqueue more microtasks, and the event loop continues processing microtasks until the queue is empty, there's a real risk of getting the event loop endlessly processing microtasks. Be cautious with how you go about recursively adding microtasks.</p>
</div>
<h2 id="Using_microtasks" name="Using_microtasks">マイクロタスクを使用する</h2>
<p>Before getting farther into this, it's important to note again that most developers won't use microtasks much, if at all. They're a highly specialized feature of modern browser-based JavaScript development, allowing you to schedule code to jump in front of other things in the long set of things waiting to happen on the user's computer. Abusing this capability will lead to performance problems.</p>
<h3 id="Enqueueing_microtasks" name="Enqueueing_microtasks">マイクロタスクをキューに入れる</h3>
<p>As such, you should typically use microtasks only when there's no other solution, or when creating frameworks or libraries that need to use microtasks in order to create the functionality they're implementing. While there have been tricks available that made it possible to enqueue microtasks in the past (such as by creating a promise that resolves immediately), the addition of the {{domxref("WindowOrWorkerGlobalScope.queueMicrotask", "queueMicrotask()")}} method adds a standard way to introduce a microtask safely and without tricks.</p>
<p>By introducing <code>queueMicrotask()</code>, the quirks that arise when sneaking in using promises to create microtasks can be avoided. For instance, when using promises to create microtasks, exceptions thrown by the callback are reported as rejected promises rather than being reported as standard exceptions. Also, creating and destroying promises takes additional overhead both in terms of time and memory that a function which properly enqueues microtasks avoids.</p>
<p>Simply pass the JavaScript {{jsxref("Function")}} to call while the context is handling microtasks into the <code>queueMicrotask()</code> method, which is exposed on the global context as defined by either the {{domxref("Window")}} or {{domxref("Worker")}} interface, depending on the current execution context.</p>
<pre class="brush: js">queueMicrotask(() => {
/* code to run in the microtask here */
});
</pre>
<p>The microtask function itself takes no parameters, and does not return a value.</p>
<h3 id="When_to_use_microtasks" name="When_to_use_microtasks">マイクロタスクを使うべきとき</h3>
<p>In this section, we'll take a look at scenarios in which microtasks are particularly useful. Generally, it's about capturing or checking results, or performing cleanup, after the main body of a JavaScript execution context exits, but before any event handlers, timeouts and intervals, or other callbacks are processed.</p>
<p>When is that useful?</p>
<p>The main reason to use microtasks is simply that: to ensure consistent ordering of tasks, even when results or data is available synchronously, but while simultaneously reducing the risk of user-discernible delays in operations.</p>
<h4 id="Ensuring_ordering_on_conditional_use_of_promises" name="Ensuring_ordering_on_conditional_use_of_promises">Promiseの条件付き使用の順番を確定させる</h4>
<p>実行順序が常に一貫するよう保証するためにマイクロタスクを使用できる状況として、Promiseが単一の <code>if...else</code> 文 (や他の条件文)の句の中にあって、他の句の内にないときです。次のコードを考えてみます:</p>
<pre class="brush: js">customElement.prototype.getData = url => {
if (this.cache[url]) {
this.data = this.cache[url];
this.dispatchEvent(new Event("load"));
} else {
fetch(url).then(result => result.arrayBuffer()).then(data => {
this.cache[url] = data;
this.data = data;
this.dispatchEvent(new Event("load"));
)};
}
};</pre>
<p>ここで入ってきた問題は、<code>if...else</code> 文 (画像がキャッシュ内で利用できる場合) の分岐内でタスクを使っているが、<code>else</code> 句でPromiseがある場合、命令の順序が変わる状況になります; 例えば、次のように。</p>
<pre class="brush: js">element.addEventListener("load", () => console.log("Loaded data"));
console.log("Fetching data...");
element.getData();
console.log("Data fetched");
</pre>
<p>このコードを行の中で2回実行すると、次の表の結果になります:</p>
<table class="standard-table">
<caption>データがキャッシュされていない (左) ときと、データがキャッシュされているときの結果</caption>
<thead>
<tr>
<th scope="col">データはキャッシュされていない</th>
<th scope="col">データはキャッシュされている</th>
</tr>
</thead>
<tbody>
<tr>
<td>
<pre>
Fetching data
Data fetched
Loaded data
</pre>
</td>
<td>
<pre>
Fetching data
Loaded data
Data fetched
</pre>
</td>
</tr>
</tbody>
</table>
<p>もっと悪いことに、このコードが実行完了となるまでに、要素の <code>data</code> プロパティは時々セットされたり、されなかったりもします。</p>
<p>これらの命令の順序を一貫させるために、マイクロタスクを <code>if</code> 句の中で使って、2つの句のバランスを取ることができます:</p>
<pre class="brush: js">customElement.prototype.getData = url => {
if (thiscache[url]) {
queueMicrotask(() => {
this.data = this.cache[url];
this.dispatchEvent(new Event("load"));
});
} else {
fetch(url).then(result => result.arrayBuffer()).then(data => {
this.cache[url] = data;
this.data = data;
this.dispatchEvent(new Event("load"));
)};
}
};</pre>
<p>両方の状況でマイクロタスク内で <code>data</code> をセットして <code>load</code> イベントを発火させる (<code>if</code> 句では <code>queueMicrotask()</code>を使い <code>else</code> 句では{{domxref("WindowOrWorkerGlobalScope.fetch", "fetch()")}} を使う) ことで、句ごとにバランスを取っています。</p>
<h4 id="Batching_operations" name="Batching_operations">バッチオペレーション</h4>
<p>You can also use microtasks to collect multiple requests from various sources into a single batch, avoiding the possible overhead involved with multiple calls to handle the same kind of work.</p>
<p>The snippet below creates a function that batches multiple messages into an array, using a microtask to send them as a single object when the context exits.</p>
<pre class="brush: js">const messageQueue = [];
let sendMessage = message => {
messageQueue.push(message);
if (messageQueue.length === 1) {
queueMicrotask(() => {
const json = JSON.stringify(messageQueue);
messageQueue.length = 0;
fetch("url-of-receiver", json);
});
}
};
</pre>
<p>When <code>sendMessage()</code> gets called, the specified message is first pushed onto the message queue array. Then things get interesting.</p>
<p>If the message we just added to the array is the first one, we enqueue a microtask that will send a batch. The microtask will execute, as always, when the JavaScript execution path reaches the top level, just before running callbacks. That means that any further calls to <code>sendMessage()</code> made in the interim will push their messages onto the message queue, but because of the array length check before adding a microtask, no new microtask is enqueued.</p>
<p>When the microtask runs, then, it has an array of potentially many messages waiting for it. It starts by encoding it as JSON using the {{jsxref("JSON.stringify()")}} method. After that, the array's contents aren't needed anymore, so we empty the <code>messageQueue</code> array. Finally, we use the {{domxref("WindowOrWorkerGlobalScope.fetch", "fetch()")}} method to send the JSON string to the server.</p>
<p>This lets every call to <code>sendMessage()</code> made during the same iteration of the event loop add their messages to the same <code>fetch()</code> operation, without potentially having other tasks such as timeouts or the like delay the transmission.</p>
<p>The server will receive the JSON string, then will presumably decode it and process the messages it finds in the resulting array.</p>
<h2 id="Examples" name="Examples">例</h2>
<h3 id="Simple_microtask_example" name="Simple_microtask_example">簡単なマイクロタスクの例</h3>
<p>In this simple example, we see that enqueueing a microtask causes the microtask's callback to run after the body of this top-level script is done running.</p>
<div class="hidden">
<h4 id="HTML" name="HTML">HTML</h4>
<pre class="brush: html"><pre id="log">
</pre></pre>
</div>
<h4 id="JavaScript" name="JavaScript">JavaScript</h4>
<div class="hidden">
<p>The code below is used to log the output.</p>
<pre class="brush: js">let logElem = document.getElementById("log");
let log = s => logElem.innerHTML += s + "<br>";</pre>
</div>
<p>In the following code, we see a call to {{domxref("WindowOrWorkerGlobalScope.queueMicrotask", "queueMicrotask()")}} used to schedule a microtask to run. This call is bracketed by calls to <code>log()</code>, a custom function that simply outputs text to the screen.</p>
<pre class="brush: js">log("Before enqueueing the microtask");
queueMicrotask(() => {
log("The microtask has run.")
});
log("After enqueueing the microtask");</pre>
<h4 id="Result" name="Result">結果</h4>
<p>{{EmbedLiveSample("Simple_microtask_example", 640, 80)}}</p>
<h3 id="Timeout_and_microtask_example" name="Timeout_and_microtask_example">Timeoutとマイクロタスクの例</h3>
<p>In this example, a timeout is scheduled to fire after zero milliseconds (or "as soon as possible"). This demonstrates the difference between what "as soon as possible" means when scheduling a new task (such as by using <code>setTimeout()</code>) versus using a microtask.</p>
<div class="hidden">
<h4 id="HTML_2" name="HTML_2">HTML</h4>
<pre class="brush: html"><pre id="log">
</pre></pre>
</div>
<h4 id="JavaScript_2" name="JavaScript_2">JavaScript</h4>
<div class="hidden">
<p>The code below is used to log the output.</p>
<pre class="brush: js">let logElem = document.getElementById("log");
let log = s => logElem.innerHTML += s + "<br>";</pre>
</div>
<p>In the following code, we see a call to {{domxref("WindowOrWorkerGlobalScope.queueMicrotask", "queueMicrotask()")}} used to schedule a microtask to run. This call is bracketed by calls to <code>log()</code>, a custom function that simply outputs text to the screen.</p>
<p>The code below schedules a timeout to occur in zero milliseconds, then enqueues a microtask. This is bracketed by calls to <code>log()</code> to output additional messages.</p>
<pre class="brush: js">let callback = () => log("Regular timeout callback has run");
let urgentCallback = () => log("*** Oh noes! An urgent callback has run!");
log("Main program started");
setTimeout(callback, 0);
queueMicrotask(urgentCallback);
log("Main program exiting");</pre>
<h4 id="Result_2" name="Result_2">結果</h4>
<p>{{EmbedLiveSample("Timeout_and_microtask_example", 640, 100)}}</p>
<p>Note that the output logged from the main program body appears first, followed by the output from the microtask, followed by the timeout's callback. That's because when the task that's handling the execution of the main program exits, the microtask queue gets processed before the task queue on which the timeout callback is located. Remembering that tasks and microtasks are kept on separate queues, and that microtasks run first will help keep this straight.</p>
<h3 id="Microtask_from_a_function" name="Microtask_from_a_function">関数からのマイクロタスク</h3>
<p>This example expands slightly on the previous one by adding a function that does some work. This function uses <code>queueMicrotask()</code> to schedule a microtask. The important thing to take away from this one is that the microtask isn't processed when the function exits, but when the main program exits.</p>
<div class="hidden">
<h4 id="HTML_3" name="HTML_3">HTML</h4>
<pre class="brush: html"><pre id="log">
</pre></pre>
</div>
<h4 id="JavaScript_3" name="JavaScript_3">JavaScript</h4>
<div class="hidden">
<p>The code below is used to log the output.</p>
<pre class="brush: js">let logElem = document.getElementById("log");
let log = s => logElem.innerHTML += s + "<br>";</pre>
</div>
<p>The main program code follows. The <code>doWork()</code> function here calls <code>queueMicrotask()</code>, yet the microtask still doesn't fire until the entire program exits, since that's when the task exits and there's nothing else on the execution stack.</p>
<pre class="brush: js">let callback = () => log("Regular timeout callback has run");
let urgentCallback = () => log("*** Oh noes! An urgent callback has run!");
let doWork = () => {
let result = 1;
queueMicrotask(urgentCallback);
for (let i=2; i<=10; i++) {
result *= i;
}
return result;
};
log("Main program started");
setTimeout(callback, 0);
log(`10! equals ${doWork()}`);
log("Main program exiting");</pre>
<h4 id="Result_3" name="Result_3">結果</h4>
<p>{{EmbedLiveSample("Microtask_from_a_function", 640, 100)}}</p>
<h2 id="See_also" name="See_also">関連情報</h2>
<ul>
<li><a href="/ja/docs/Web/API/HTML_DOM_API/Microtask_guide/In_depth">In depth: Microtasks and the JavaScript runtime environment</a></li>
<li>{{domxref("WindowOrWorkerGlobalScope.queueMicrotask", "queueMicrotask()")}}</li>
<li><a href="/ja/docs/Learn/JavaScript/Asynchronous">Asynchronous JavaScript</a>
<ul>
<li><a href="/ja/docs/Learn/JavaScript/Asynchronous/Concepts">General asynchronous programming concepts</a></li>
<li><a href="/ja/docs/Learn/JavaScript/Asynchronous/Introducing">Introducing asynchronous JavaScript</a></li>
<li><a href="/ja/docs/Learn/JavaScript/Asynchronous/Timeouts_and_intervals">Cooperative asynchronous JavaScript: Timeouts and intervals</a></li>
<li><a href="/ja/docs/Learn/JavaScript/Asynchronous/Promises">Graceful asynchronous programming with Promises</a></li>
<li><a href="/ja/docs/Learn/JavaScript/Asynchronous/Choosing_the_right_approach">Choosing the right approach</a></li>
</ul>
</li>
</ul>
|