You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Copy file name to clipboardExpand all lines: 2-ui/99-ui-misc/03-event-loop/article.md
+49-50Lines changed: 49 additions & 50 deletions
Display the source diff
Display the rich diff
Original file line number
Diff line number
Diff line change
@@ -1,7 +1,7 @@
1
1
2
2
# Event loop: microtasks e macrotasks
3
3
4
-
Il flusso di esecuzione di Javascript ed anche di Node.js, sono basati sull' *event loop*.
4
+
Il flusso di esecuzione di Javascript, così come quello di Node.js, sono basati sull' *event loop*.
5
5
6
6
Comprendere come un event loop lavora è importante per le ottimizzazioni, ed a volte, anche per creare delle architetture migliori.
7
7
@@ -206,41 +206,43 @@ Questo sembra più carino:
206
206
</script>
207
207
```
208
208
209
-
Adesso il `<div>` mostra via via, valori crescenti di `i`, una sorta di barra di caricamento.
210
-
209
+
Adesso il `<div>` mostra via via, valori crescenti di `i`,come se fosse una sorta di barra di caricamento.
211
210
212
211
213
212
## Caso d'uso 3: fare qualcosa dopo l'evento
214
213
215
-
In un gestore di evento noi potremmo decidere di postporre alcune azioni, fino a che l'evento non risalga i vari livelli di stack (bubbling up) e non venga gestito su tutti questi livelli. Possiamo fare questo, avvolgendo (wrapping) il codice all'interno di `setTimeout` a latenza zero.
214
+
In un gestore di evento, potremmo decidere di postporre alcune azioni, fino a che l'evento non risalga i vari livelli di stack (bubbling up) e non venga gestito su tutti questi livelli.
215
+
Possiamo farlo, avvolgendo (wrapping) il codice all'interno dei `setTimeout` a ritardo zero.
216
+
217
+
Nel capitolo <info:dispatch-events> abbiamo visto un esempio: dell'evento custom `menu-open`, viene fatto il dispatch dentro `setTimeout`, così che esso viene richiamato dopo che l'evento click è stto del tutto gestito.
216
218
217
-
Nel capitolo In the chapter <info:dispatch-events> we saw an example: custom event `menu-open` is dispatched in `setTimeout`, so that it happens after the "click" event is fully handled.
218
219
219
220
```js
220
221
menu.onclick=function() {
221
222
// ...
222
223
223
-
// create a custom event with the clicked menu item data
224
+
//crea un evento custom con l'elemento dati cliccato sul menu'
224
225
let customEvent =newCustomEvent("menu-open", {
225
226
bubbles:true
226
227
});
227
228
228
-
//dispatch the custom event asynchronously
229
+
//dispatch dell'evento custom in maniera asincrona
229
230
setTimeout(() =>menu.dispatchEvent(customEvent));
230
231
};
231
232
```
232
233
233
-
## Macrotasks and Microtasks
234
+
## Macrotasks e Microtasks
235
+
234
236
235
-
Along with*macrotasks*, described in this chapter, there exist*microtasks*, mentioned in the chapter<info:microtask-queue>.
237
+
insieme ai*macrotasks*, descritti in questo capitolo, esistono i*microtasks*, menzionati nel capitolo<info:microtask-queue>.
236
238
237
-
Microtasks come solely from our code. They are usually created by promises: an execution of `.then/catch/finally`handler becomes a microtask. Microtasks are used "under the cover" of `await` as well, as it's another form of promise handling.
239
+
Microtasks provengono esclusivamente dal nostro codice. Solitamente vengono creati dalle promises: una esecuzione di un gestore `.then/catch/finally`diventa un microtask. I microtasks vengono usati anche "sotto copertura" dagli `await`, dato che anche questi sono solo un'altra forma di gestione delle promise.
238
240
239
-
There's also a special function`queueMicrotask(func)`that queues`func` for execution in the microtask queue.
241
+
C'è anche una funzione speciale`queueMicrotask(func)`che accoda`func`per l'esecuzione nella coda dei microtask.
240
242
241
-
**Immediately after every*macrotask*, the engine executes all tasks from *microtask* queue, prior to running any other macrotasks or rendering or anything else.**
243
+
**Immediatamente dopo ogni*macrotask*, il motore esegue tutti i task dalla coda *microtask* queue, prima di ricominciare a eseguire ogni altro macrotask o renderizzare o qualunque altra cosa.**
242
244
243
-
For instance, take a look:
245
+
Per esempio, guardate questo:
244
246
245
247
```js run
246
248
setTimeout(() =>alert("timeout"));
@@ -251,23 +253,24 @@ Promise.resolve()
251
253
alert("code");
252
254
```
253
255
254
-
What's going to be the order here?
256
+
Che sta succedendo all'ordine qui?
255
257
256
-
1.`code`shows first, because it's a regular synchronous call.
257
-
2.`promise`shows second, because`.then`passes through the microtask queue, and runs after the current code.
258
-
3.`timeout`shows last, because it's a macrotask.
258
+
1.`code`viene mostrato prima, dato che è è un chiamata regolare e sincrona.
259
+
2.`promise`viene mostrato per secondo, perchè`.then`passa attraverso la coda di microtask, e viene eseguito dopo il codice corrente.
260
+
3.`timeout`viene mostrato come ultimo perchè è anhe questo un microtask.
259
261
260
-
The richer event loop picture looks like this:
262
+
L'immagine più esausitva di un event loop è è questa:
261
263
262
264

263
265
264
-
**All microtasks are completed before any other event handling or rendering or any other macrotask takes place.**
266
+
**Tutti i microtasks vengono completati prima di ogni altra gestione degli eventi o rendering o qualunque altro macrotask che prende parte nell'esecuzione**
265
267
266
-
That's important, as it guarantees that the application environment is basically the same (no mouse coordinate changes, no new network data, etc) between microtasks.
268
+
Questo è importante perchè garantisce che l'ambiente applicativo rimanga intatto (nessuna modifica alle coordinate del puntatore del mouse, nessun dato dalle reti, etc) tra i microtasks.
267
269
268
-
If we'd like to execute a function asynchronously (after the current code), but before changes are rendered or new events handled, we can schedule it with`queueMicrotask`.
270
+
Se volessimo eseguire una funzione in maniera asincrona (dopo il codice in esecuzione), ma prima che avvengano cambiamenti nella finestra del browser, o nuvi eventi vengano gestiti, potremmo schedularla con`queueMicrotask`.
269
271
270
-
Here's an example with "counting progress bar", similar to the one shown previously, but `queueMicrotask` is used instead of `setTimeout`. You can see that it renders at the very end. Just like the synchronous code:
272
+
Questo qui un esempio con la "conteggio barra di progresso", del tutto simi a quella precedente, ma vengono usati `queueMicrotask` invece di `setTimeout`.
273
+
Come puoi vedere che renderizza alla fine. Esattamente come se fosse del codice sincrono:
271
274
272
275
```html run
273
276
<divid="progress"></div>
@@ -276,62 +279,58 @@ Here's an example with "counting progress bar", similar to the one shown previou
276
279
let i =0;
277
280
278
281
functioncount() {
279
-
280
-
// do a piece of the heavy job (*)
282
+
//faccio un pezzetto di lavoro pesante (*)
281
283
do {
282
284
i++;
283
285
progress.innerHTML= i;
284
286
} while (i %1e3!=0);
285
287
286
288
if (i <1e6) {
287
-
*!*
288
-
queueMicrotask(count);
289
-
*/!*
289
+
queueMicrotask(count);
290
290
}
291
-
292
291
}
293
292
294
293
count();
295
294
</script>
296
295
```
297
296
298
-
## Summary
297
+
## Conclusioni
299
298
300
-
The richer event loop picture may look like this:
299
+
L'immagine più esausitva di un event loop è questa:
301
300
302
301

303
302
304
-
The more detailed algorithm of the event loop (though still simplified compare to the[specification](https://html.spec.whatwg.org/multipage/webappapis.html#event-loop-processing-model)):
303
+
Il più dettagliato algoritmo dell'event loop (sebbene ancora semplicistico rispetto alla[specification](https://html.spec.whatwg.org/multipage/webappapis.html#event-loop-processing-model)):
305
304
306
-
1.Dequeue and run the oldest task from the *macrotask*queue (e.g. "script").
307
-
2.Execute all*microtasks*:
308
-
-While the microtask queue is not empty:
309
-
-Dequeue and run the oldest microtask.
310
-
3.Render changes if any.
311
-
4.If the macrotask queue is empty, wait till a macrotask appears.
312
-
5.Go to step 1.
305
+
1.Rimuovi dalla coda ed esegui, il più vecchio task dalla coda dei *macrotask* (ad esempio "script").
306
+
2.Eseguit tutti i*microtasks*:
307
+
-Se la cosa dei microtask non è vuota:
308
+
-Rimuovi dalla coda ed esegui il più vecchio dei microtask.
309
+
3.Renderizza le modifiche se ve ne sono.
310
+
4.Se la coda dei macrotask è vuota, vai in sleep fino al prossimo macrotask.
311
+
5.Vai al passo 1.
313
312
314
-
To schedule a new*macrotask*:
313
+
Per schedulare un nuovo*macrotask*:
315
314
- Use zero delayed `setTimeout(f)`.
316
315
317
-
That may be used to split a big calculation-heavy task into pieces, for the browser to be able to react on user events and show progress between them.
316
+
Questo potrebbe essere usato per divitere task di calcolopesante in pezzi, di modo che tra questi, il browser possa eseguire altre operazioni.
318
317
319
-
Also, used in event handlers to schedule an action after the event is fully handled (bubbling done).
318
+
Inoltre, vengono usati nei gestori degli eventi per schedulre una azione dopo che l'evento è stato del tutto gestito (bubbling completato)
320
319
321
-
To schedule a new*microtask*
322
-
-Use`queueMicrotask(f)`.
323
-
-Also promise handlers go through the microtask queue.
320
+
Per schedulare un nuovo*microtask*
321
+
-Usa`queueMicrotask(f)`.
322
+
-Anche i gestori promise passando attraverso la coda dei microtask.
324
323
325
-
There's no UI or network event handling between microtasks: they run immediately one after another.
324
+
Non ci sono gestori UI o di networking tra i microtask: vengono eseguiti immediatamente uno dopo l'altro
326
325
327
-
So one may want to `queueMicrotask`to execute a function asynchronously, but within the environment state.
326
+
Quindi uno potrebbe volere che la coda `queueMicrotask`eseguisse una funzione in maniera asincrona, ma manntenendo il contesto dell'ambiente.
328
327
329
328
```smart header="Web Workers"
330
-
For long heavy calculations that shouldn't block the event loop, we can use [Web Workers](https://html.spec.whatwg.org/multipage/workers.html).
329
+
Per lunghi calcoli pesanti che non possono bloccare l'event loop, possiamo usare i [Web Workers](https://html.spec.whatwg.org/multipage/workers.html).
331
330
332
-
That's a way to run code in another, parallel thread.
331
+
Che è un modo per eseguire del codice in un altro thread parallelo.
333
332
334
-
Web Workers can exchange messages with the main process, but they have their own variables, and their own event loop.
333
+
I Web Workers possono scambiarsi messaggi con il processo principale, ma hanno le loro variabili ed i loro event loop.
335
334
336
-
Web Workers do not have access to DOM, so they are useful, mainly, for calculations, to use multiplle CPU cores simultaneously.
335
+
I Web Workers non hanno accesso al DOM, quindi sono adatti principalmente per i calcoli, per usare contemporaneamente più cores CPU.
0 commit comments