Skip to content

Commit 734ed1a

Browse files
Update article.md
1 parent 73605fd commit 734ed1a

File tree

1 file changed

+49
-50
lines changed

1 file changed

+49
-50
lines changed

2-ui/99-ui-misc/03-event-loop/article.md

Lines changed: 49 additions & 50 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11

22
# Event loop: microtasks e macrotasks
33

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&igrave come quello di Node.js, sono basati sull' *event loop*.
55

66
Comprendere come un event loop lavora è importante per le ottimizzazioni, ed a volte, anche per creare delle architetture migliori.
77

@@ -206,41 +206,43 @@ Questo sembra più carino:
206206
</script>
207207
```
208208

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

212211

213212
## Caso d'uso 3: fare qualcosa dopo l'evento
214213

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&igrave; che esso viene richiamato dopo che l'evento click è stto del tutto gestito.
216218

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

219220
```js
220221
menu.onclick = function() {
221222
// ...
222223

223-
// create a custom event with the clicked menu item data
224+
//crea un evento custom con l'elemento dati cliccato sul menu'
224225
let customEvent = new CustomEvent("menu-open", {
225226
bubbles: true
226227
});
227228

228-
// dispatch the custom event asynchronously
229+
//dispatch dell'evento custom in maniera asincrona
229230
setTimeout(() => menu.dispatchEvent(customEvent));
230231
};
231232
```
232233

233-
## Macrotasks and Microtasks
234+
## Macrotasks e Microtasks
235+
234236

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

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

239-
There's also a special function `queueMicrotask(func)` that queues `func` for execution in the microtask queue.
241+
C'&egrave; anche una funzione speciale `queueMicrotask(func)` che accoda `func`per l'esecuzione nella coda dei microtask.
240242

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.**
242244

243-
For instance, take a look:
245+
Per esempio, guardate questo:
244246

245247
```js run
246248
setTimeout(() => alert("timeout"));
@@ -251,23 +253,24 @@ Promise.resolve()
251253
alert("code");
252254
```
253255

254-
What's going to be the order here?
256+
Che sta succedendo all'ordine qui?
255257

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 è &egrave; un chiamata regolare e sincrona.
259+
2. `promise` viene mostrato per secondo, perch&egrave; `.then` passa attraverso la coda di microtask, e viene eseguito dopo il codice corrente.
260+
3. `timeout` viene mostrato come ultimo perch&egrave; è anhe questo un microtask.
259261

260-
The richer event loop picture looks like this:
262+
L'immagine pi&ugrave; esausitva di un event loop &egrave; è questa:
261263

262264
![](eventLoop-full.svg)
263265

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

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 &egrave; importante perch&egrave; garantisce che l'ambiente applicativo rimanga intatto (nessuna modifica alle coordinate del puntatore del mouse, nessun dato dalle reti, etc) tra i microtasks.
267269

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`.
269271

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

272275
```html run
273276
<div id="progress"></div>
@@ -276,62 +279,58 @@ Here's an example with "counting progress bar", similar to the one shown previou
276279
let i = 0;
277280
278281
function count() {
279-
280-
// do a piece of the heavy job (*)
282+
//faccio un pezzetto di lavoro pesante (*)
281283
do {
282284
i++;
283285
progress.innerHTML = i;
284286
} while (i % 1e3 != 0);
285287
286288
if (i < 1e6) {
287-
*!*
288-
queueMicrotask(count);
289-
*/!*
289+
queueMicrotask(count);
290290
}
291-
292291
}
293292
294293
count();
295294
</script>
296295
```
297296

298-
## Summary
297+
## Conclusioni
299298

300-
The richer event loop picture may look like this:
299+
L'immagine pi&ugrave; esausitva di un event loop &egrave; questa:
301300

302301
![](eventLoop-full.svg)
303302

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)):
305304

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

314-
To schedule a new *macrotask*:
313+
Per schedulare un nuovo *macrotask*:
315314
- Use zero delayed `setTimeout(f)`.
316315

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

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

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

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
326325

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

329328
```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).
331330
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.
333332
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.
335334
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.
337336
```

0 commit comments

Comments
 (0)