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
+73-72Lines changed: 73 additions & 72 deletions
Display the source diff
Display the rich diff
Original file line number
Diff line number
Diff line change
@@ -1,64 +1,64 @@
1
1
2
-
# Event loop: microtasks and macrotasks
2
+
# Olay döngüsü: microtasks ve macrotasks
3
3
4
-
Browser JavaScript execution flow, as well as in Node.js, is based on an *event loop*.
4
+
Node.js'de olduğu gibi tarayıcı JavaScript yürütme akışı da bir *olay döngüsüne* dayanır.
5
5
6
-
Understanding how event loop works is important for optimizations, and sometimes for the right architecture.
6
+
Olay döngüsünün nasıl çalıştığını anlamak, optimizasyonlar ve bazen de doğru mimari için önemlidir.
7
7
8
-
In this chapter we first cover theoretical details about how things work, and then see practical applications of that knowledge.
8
+
Bu bölümde önce işlerin nasıl yürüdüğüyle ilgili teorik ayrıntıları ele alacağız ve ardından bu bilginin pratik uygulamalarını göreceğiz.
9
9
10
-
## Event Loop
10
+
## Olay Döngüsü
11
11
12
-
The *event loop* concept is very simple. There's an endless loop, where the JavaScript engine waits for tasks, executes them and then sleeps, waiting for more tasks.
12
+
*Olay döngüsü* kavramı çok basittir. JavaScript motorunun görevleri beklediği, yürüttüğü ve daha sonra uyuyarak daha fazla görev beklediği sonsuz bir döngü vardır.
13
13
14
-
The general algorithm of the engine:
14
+
Motorun genel algoritması:
15
15
16
-
1.While there are tasks:
17
-
-execute them, starting with the oldest task.
18
-
2.Sleep until a task appears, then go to 1.
16
+
1.Görevler varken:
17
+
-en eski görevden başlayarak bunları yürütün.
18
+
2.Bir görev görünene kadar uyuyun, ardından 1'e gidin.
19
19
20
-
That's a formalization for what we see when browsing a page. The JavaScript engine does nothing most of the time, it only runs if a script/handler/event activates.
20
+
Bu, bir sayfaya göz atarken gördüğümüz şeyin biçimselleştirilmesidir. JavaScript motoru çoğu zaman hiçbir şey yapmaz, yalnızca bir script/işleyici/olay etkinleştirildiğinde çalışır.
21
21
22
-
Examples of tasks:
22
+
Görev örnekleri:
23
23
24
-
-When an external script `<script src="...">`loads, the task is to execute it.
25
-
-When a user moves their mouse, the task is to dispatch `mousemove`event and execute handlers.
26
-
-When the time is due for a scheduled `setTimeout`, the task is to run its callback.
27
-
- ...and so on.
24
+
-Harici bir script `<script src="...">`yüklendiğinde, görev onu yürütmektir.
25
+
-Bir kullanıcı faresini hareket ettirdiğinde, görev `mousemove`olayını göndermek ve işleyicileri yürütmektir.
26
+
-Zamanlanmış bir `setTimeout` için zaman geldiğinde, görev callback'i çalıştırmaktır.
27
+
- ...ve benzeri.
28
28
29
-
Tasks are set -- the engine handles them -- then waits for more tasks (while sleeping and consuming close to zero CPU).
29
+
Görevler belirlenir - motor bunları işler - sonra daha fazla görev bekler (uyurken ve sıfıra yakın CPU tüketirken).
30
30
31
-
It may happen that a task comes while the engine is busy, then it's enqueued.
31
+
Motor meşgulken bir görev gelebilir, sonra sıraya girebilir.
32
32
33
-
The tasks form a queue, so-called "macrotask queue" (v8 term):
33
+
Görevler, "macrotask sırası" (v8 terimi) olarak adlandırılan bir sıra oluşturur:
34
34
35
35

36
36
37
-
For instance, while the engine is busy executing a `script`, a user may move their mouse causing`mousemove`, and `setTimeout`may be due and so on, these tasks form a queue, as illustrated on the picture above.
37
+
Örneğin, motor bir `script`'i yürütmekle meşgulken, bir kullanıcı faresini hareket ettirerek`mousemove`'a neden olabilir ve `setTimeout`zamanı gelmiş olabilir ve benzeri, yukarıdaki resimde gösterildiği gibi bu görevler bir kuyruk oluşturur.
38
38
39
-
Tasks from the queue are processed on "first come – first served" basis. When the engine browser is done with the `script`, it handles `mousemove`event, then`setTimeout`handler, and so on.
39
+
Kuyruktaki görevler "ilk gelene ilk hizmet" esasına göre işlenir. Tarayıcı motoru `script` ile işi bittiğinde, `mousemove`olayını, ardından`setTimeout`işleyicisini vb. işler.
40
40
41
-
So far, quite simple, right?
41
+
Buraya kadar oldukça basit, değil mi?
42
42
43
-
Two more details:
44
-
1.Rendering never happens while the engine executes a task. It doesn't matter if the task takes a long time. Changes to the DOM are painted only after the task is complete.
45
-
2.If a task takes too long, the browser can't do other tasks, such as processing user events. So after a time, it raises an alert like "Page Unresponsive", suggesting killing the task with the whole page. That happens when there are a lot of complex calculations or a programming error leading to an infinite loop.
43
+
İki ayrıntı daha:
44
+
1.Motor bir görevi yürütürken oluşturma(Render) asla gerçekleşmez. Görevin uzun sürmesi önemli değil. DOM'daki değişiklikler yalnızca görev tamamlandıktan sonra boyanır.
45
+
2.Bir görev çok uzun sürerse tarayıcı, kullanıcı olaylarını işleme gibi diğer görevleri yapamaz. Bu yüzden bir süre sonra "Sayfa Yanıt Vermiyor" gibi bir uyarı vererek görevi tüm sayfayla sonlandırmayı önerir. Bu, çok sayıda karmaşık hesaplama olduğunda veya sonsuz bir döngüye yol açan bir programlama hatası olduğunda olur.
46
46
47
-
That was the theory. Now let's see how we can apply that knowledge.
47
+
Teori buydu. Şimdi bu bilgiyi nasıl uygulayabileceğimizi görelim.
48
48
49
-
## Use-case 1: splitting CPU-hungry tasks
49
+
## Kullanım Senaryosu 1: CPU'ya aç görevleri bölme
50
50
51
-
Let's say we have a CPU-hungry task.
51
+
Diyelim ki CPU'ya aç bir görevimiz var.
52
52
53
-
For example, syntax-highlighting (used to colorize code examples on this page) is quite CPU-heavy. To highlight the code, it performs the analysis, creates many colored elements, adds them to the document -- for a large amount of text that takes a lot of time.
53
+
Örneğin, sözdizimi vurgulama(syntax-highlighting) (bu sayfadaki kod örneklerini renklendirmek için kullanılır) oldukça CPU ağırlıklıdır. Kodu vurgulamak için, analizi gerçekleştirir, birçok renkli öğe oluşturur, bunları belgeye ekler - çok fazla zaman alan büyük miktarda metin için.
54
54
55
-
While the engine is busy with syntax highlighting, it can't do other DOM-related stuff, process user events, etc. It may even cause the browser to "hiccup" or even "hang" for a bit, which is unacceptable.
55
+
Motor sözdizimi vurgulama ile meşgulken, DOM ile ilgili diğer işlemleri yapamaz, kullanıcı olaylarını işleyemez vb. Hatta tarayıcının bir süre "hıçkırmasına" ve hatta "takılmasına" neden olabilir ki bu kabul edilemez bir durumdur.
56
56
57
-
We can avoid problems by splitting the big task into pieces. Highlight first 100 lines, then schedule `setTimeout` (with zero-delay) for the next 100 lines, and so on.
57
+
Büyük görevi parçalara bölerek sorunlardan kaçınabiliriz. İlk 100 satırı vurgulayın, ardından sonraki 100 satır için "setTimeout" (sıfır gecikmeli) zamanlayın, vb.
58
58
59
-
To demonstrate this approach, for the sake of simplicity, instead of text-highlighting, let's take a function that counts from `1`to`1000000000`.
59
+
Bu yaklaşımı göstermek için, basitlik adına, metin vurgulama yerine `1`ile`1000000000` arasında sayan bir fonksiyon alalım.
60
60
61
-
If you run the code below, the engine will "hang" for some time. For server-side JS that's clearly noticeable, and if you are running it in-browser, then try to click other buttons on the page -- you'll see that no other events get handled until the counting finishes.
61
+
Aşağıdaki kodu çalıştırırsanız, motor bir süre "askıda kalır". Açıkça fark edilen sunucu tarafı JS için ve tarayıcıda çalıştırıyorsanız, sayfadaki diğer düğmeleri tıklamayı deneyin - sayım bitene kadar başka hiçbir olayın işlenmediğini göreceksiniz.
62
62
63
63
```js run
64
64
let i =0;
@@ -67,7 +67,7 @@ let start = Date.now();
67
67
68
68
functioncount() {
69
69
70
-
//do a heavy job
70
+
//ağır bir iş yap
71
71
for (let j =0; j <1e9; j++) {
72
72
i++;
73
73
}
@@ -78,9 +78,9 @@ function count() {
78
78
count();
79
79
```
80
80
81
-
The browser may even show a "the script takes too long" warning.
81
+
Tarayıcı, "script çok uzun sürüyor" uyarısı bile gösterebilir.
82
82
83
-
Let's split the job using nested `setTimeout`calls:
83
+
İşi iç içe `setTimeout`çağrılarını kullanarak bölelim:
84
84
85
85
```js run
86
86
let i =0;
@@ -89,37 +89,38 @@ let start = Date.now();
89
89
90
90
functioncount() {
91
91
92
-
//do a piece of the heavy job (*)
92
+
//ağır işin bir parçasını yap (*)
93
93
do {
94
94
i++;
95
95
} while (i %1e6!=0);
96
96
97
97
if (i ==1e9) {
98
98
alert("Done in "+ (Date.now() - start) +'ms');
99
99
} else {
100
-
setTimeout(count); //schedule the new call (**)
100
+
setTimeout(count); //yeni cağrıyı planla (**)
101
101
}
102
102
103
103
}
104
104
105
105
count();
106
106
```
107
107
108
-
Now the browser interface is fully functional during the "counting" process.
108
+
Artık tarayıcı arayüzü "sayma" işlemi sırasında tamamen işlevseldir.
109
109
110
110
A single run of `count` does a part of the job `(*)`, and then re-schedules itself `(**)` if needed:
111
+
Tek bir `count` çalıştırması `(*)` işinin bir bölümünü yapar ve ardından gerekirse kendisini `(**)` olarak yeniden zamanlar:
111
112
112
-
1.First run counts: `i=1...1000000`.
113
-
2.Second run counts: `i=1000001..2000000`.
114
-
3. ...and so on.
113
+
1.İlk çalıştırma sayar: `i=1...1000000`.
114
+
2.İkinci çalıştırma sayar: `i=1000001..2000000`.
115
+
3. ...ve benzeri.
115
116
116
-
Now, if a new side task (e.g.`onclick`event) appears while the engine is busy executing part 1, it gets queued and then executes when part 1 finished, before the next part. Periodic returns to the event loop between `count`executions provide just enough "air" for the JavaScript engine to do something else, to react to other user actions.
117
+
Şimdi, motor bölüm 1'i yürütmekle meşgulken yeni bir yan görev (örneğin`onclick`olayı) ortaya çıkarsa, sıraya alınır ve sonraki bölümden önce bölüm 1 bittiğinde yürütülür. `count`yürütmeleri arasındaki olay döngüsüne periyodik geri dönüşler, JavaScript motorunun başka bir şey yapması, diğer kullanıcı eylemlerine tepki vermesi için yeterli "hava" sağlar.
117
118
118
-
The notable thing is that both variants -- with and without splitting the job by `setTimeout`-- are comparable in speed. There's not much difference in the overall counting time.
119
+
Dikkate değer olan şey, her iki varyantın da -- işi `setTimeout` ile bölerek ve bölmeden -- hız açısından karşılaştırılabilir olmasıdır. Toplam sayım süresinde pek bir fark yok.
119
120
120
-
To make them closer, let's make an improvement.
121
+
Onları daha da yakınlaştırmak için bir iyileştirme yapalım.
121
122
122
-
We'll move the scheduling to the beginning of the `count()`:
123
+
Zamanlamayı `count()`un başına taşıyacağız:
123
124
124
125
```js run
125
126
let i =0;
@@ -128,9 +129,9 @@ let start = Date.now();
128
129
129
130
functioncount() {
130
131
131
-
//move the scheduling to the beginning
132
+
//zamanlamayı en başa taşı
132
133
if (i <1e9-1e6) {
133
-
setTimeout(count); //schedule the new call
134
+
setTimeout(count); //yeni cağrıyı planla
134
135
}
135
136
136
137
do {
@@ -146,25 +147,25 @@ function count() {
146
147
count();
147
148
```
148
149
149
-
Now when we start to `count()`and see that we'll need to `count()`more, we schedule that immediately, before doing the job.
150
+
Şimdi `count()`yapmaya başladığımızda ve daha fazla `count()`yapmamız gerektiğini gördüğümüzde, işi yapmadan önce bunu hemen zamanlıyoruz.
150
151
151
-
If you run it, it's easy to notice that it takes significantly less time.
152
+
Çalıştırırsanız, önemli ölçüde daha az zaman aldığını fark etmek kolaydır.
152
153
153
-
Why?
154
+
Neden?
154
155
155
-
That's simple: as you remember, there's the in-browser minimal delay of 4ms for many nested `setTimeout`calls. Even if we set `0`, it's `4ms` (or a bit more). So the earlier we schedule it - the faster it runs.
156
+
Çok basit: Hatırladığınız gibi, iç içe geçmiş birçok `setTimeout`çağrısı için tarayıcıda minimum 4 ms gecikme vardır. `0` ayarlasak bile, `4ms` (veya biraz daha fazla). Yani ne kadar erken zamanlarsak o kadar hızlı çalışır.
156
157
157
-
Finally, we've split a CPU-hungry task into parts - now it doesn't block the user interface. And its overall execution time isn't much longer.
158
+
Son olarak, CPU'ya aç bir görevi parçalara ayırdık - artık kullanıcı arayüzünü engellemiyor. Ve genel yürütme süresi çok daha uzun değil.
158
159
159
-
## Use case 2: progress indication
160
+
## Kullanım Senaryosu 2: ilerleme göstergesi
160
161
161
-
Another benefit of splitting heavy tasks for browser scripts is that we can show progress indication.
162
+
Tarayıcı komut dosyaları için ağır görevleri bölmenin bir başka yararı da ilerleme göstergesi gösterebilmemizdir.
162
163
163
-
As mentioned earlier, changes to DOM are painted only after the currently running task is completed, irrespective of how long it takes.
164
+
Daha önce belirtildiği gibi, DOM'daki değişiklikler, ne kadar sürdüğüne bakılmaksızın, yalnızca şu anda çalışan görev tamamlandıktan sonra boyanır.
164
165
165
-
On one hand, that's great, because our function may create many elements, add them one-by-one to the document and change their styles -- the visitor won't see any "intermediate", unfinished state. An important thing, right?
166
+
Bir yandan, bu harika, çünkü fonksiyonumuz birçok öğe oluşturabilir, bunları tek tek belgeye ekleyebilir ve stillerini değiştirebilir -- ziyaretçi herhangi bir "ara", tamamlanmamış durum görmez. Önemli bir şey, değil mi?
166
167
167
-
Here's the demo, the changes to `i` won't show up until the function finishes, so we'll see only the last value:
168
+
İşte demo, `i`'deki değişiklikler fonksiyon bitene kadar görünmeyecek, bu yüzden yalnızca son değeri göreceğiz:
168
169
169
170
170
171
```html run
@@ -183,11 +184,11 @@ Here's the demo, the changes to `i` won't show up until the function finishes, s
183
184
</script>
184
185
```
185
186
186
-
...But we also may want to show something during the task, e.g. a progress bar.
187
+
...Ancak görev sırasında da bir şey göstermek isteyebiliriz, örneğin bir ilerleme çubuğu.
187
188
188
-
If we split the heavy task into pieces using `setTimeout`, then changes are painted out in-between them.
189
+
Eğer ağır görevi `setTimeout` kullanarak parçalara ayırırsak, o zaman değişiklikler aralarında boyanır.
189
190
190
-
This looks prettier:
191
+
Bu daha güzel görünüyor:
191
192
192
193
```html run
193
194
<divid="progress"></div>
@@ -197,7 +198,7 @@ This looks prettier:
197
198
198
199
functioncount() {
199
200
200
-
//do a piece of the heavy job (*)
201
+
//ağır işin bir parçasını yap (*)
201
202
do {
202
203
i++;
203
204
progress.innerHTML= i;
@@ -213,14 +214,14 @@ This looks prettier:
213
214
</script>
214
215
```
215
216
216
-
Now the `<div>` shows increasing values of `i`, a kind of a progress bar.
217
+
Şimdi `<div>`, bir tür ilerleme çubuğu olan `i`'nin artan değerlerini gösteriyor.
217
218
218
219
219
-
## Use case 3: doing something after the event
220
+
## Kullanım Senaryosu 3: olaydan sonra bir şeyler yapmak
220
221
221
-
In an event handler we may decide to postpone some actions until the event bubbled up and was handled on all levels. We can do that by wrapping the code in zero delay `setTimeout`.
222
+
Bir olay işleyicide, bazı eylemleri olay kabarıp tüm seviyelerde işlenene kadar ertelemeye karar verebiliriz. Bunu, kodu sıfır gecikmeli `setTimeout` içine sararak yapabiliriz.
222
223
223
-
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.
224
+
<info:dispatch-events>bölümünde bir örnek gördük: `menu-open`özel olayı(custom event)`setTimeout` içinde gönderilir, böylece click" olayı tamamen işlendikten sonra gerçekleşir.
224
225
225
226
```js
226
227
menu.onclick=function() {
@@ -236,17 +237,17 @@ menu.onclick = function() {
236
237
};
237
238
```
238
239
239
-
## Macrotasks and Microtasks
240
+
## Macrotasks ve Microtasks
240
241
241
-
Along with *macrotasks*, described in this chapter, there are *microtasks*, mentioned in the chapter <info:microtask-queue>.
242
+
Bu bölümde açıklanan *macrotasks* ile birlikte, <info:microtasks-sırası> bölümünde bahsedilen *microtasks* vardır.
242
243
243
-
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.
244
+
Microtask'ler yalnızca kodumuzdan gelir. Genellikle promise'larla oluşturulurlar: `.then/catch/finally`işleyicisinin yürütülmesi bir microtask haline gelir. Microtask'ler, bir başka promise işleme biçimi olduğu için, `wait`'in "örtüsü altında" da kullanılır.
244
245
245
-
There's also a special function `queueMicrotask(func)` that queues `func` for execution in the microtask queue.
246
+
Ayrıca, microtask kuyruğunda yürütülmek üzere `func`'u sıraya sokan özel bir `queueMicrotask(func)` fonksiyonu da vardır.
246
247
247
-
**Immediately after every *macrotask*, the engine executes all tasks from *microtask* queue, prior to running any other macrotasks or rendering or anything else.**
248
+
**Her macrotask'dan hemen sonra, motor, diğer macrotask'ları çalıştırmadan veya oluşturmadan veya başka herhangi bir şeyden önce tüm görevleri microtask kuyruğundan yürütür.**
0 commit comments