Hari 25: Web Workers & Concurrency
55 min
Last updated 09 Apr 2026
JavaScript adalah Single-Threaded
JavaScript berjalan pada satu thread (main thread). Operasi berat akan memblokir UI. Web Workers memungkinkan kode berjalan di thread terpisah.
// main.js
const worker = new Worker("worker.js");
worker.postMessage({ tipe: "hitung", data: 1000000 });
worker.onmessage = (event) => {
console.log("Hasil:", event.data.hasil);
};
// worker.js
self.onmessage = (event) => {
const { tipe, data } = event.data;
if (tipe === "hitung") {
let total = 0;
for (let i = 1; i <= data; i++) total += i;
self.postMessage({ hasil: total });
}
};
Event Loop & Microtasks
console.log("1 - sync");
Promise.resolve().then(() => console.log("3 - microtask"));
setTimeout(() => console.log("4 - macrotask"), 0);
console.log("2 - sync");
// Output: 1, 2, 3, 4
// Urutan: sync → microtasks → macrotasks
💡
Notice: Urutan: Sync code → Microtask queue (Promises, queueMicrotask) → Macrotask queue (setTimeout, setInterval). Microtasks SELALU selesai sebelum macrotask berikutnya.
Assignment
Demonstrasikan event loop dengan kode yang menampilkan urutan eksekusi sync, Promise (microtask), dan setTimeout (macrotask).
Expected output:
A - sync 1
B - sync 2
C - microtask 1
G - microtask 3
F - microtask 2
D - macrotask 1
E - macrotask 2
JS
script.js
Solution
Output