~/
hackweb.dev
Async JavaScript
Quiz
⌘K
...
~/
/tutorials
/js/js-async-js/edit
~ Contribute
Suggest a correction or improvement. The author reviews it before it goes live.
Loading...
Comment
0 / 300
Typo
Grammar
Broken link
Clarify
Code
en/tutorials/js/28js-async-js
Write
Preview
Diff
# Async JavaScript JavaScript handles asynchronous operations using the event loop, callbacks, and modern async patterns. ## Synchronous vs Asynchronous Synchronous code blocks each line. Async code runs in the background. ```javascript console.log("Start"); setTimeout(() => console.log("Async"), 1000); console.log("End"); // Output: Start, End, Async ``` **Remember:** Without async, the entire UI freezes during long operations. ## The Call Stack JavaScript executes one function at a time via a stack. ```javascript function third() { console.log("Third"); } function second() { third(); console.log("Second"); } function first() { second(); console.log("First"); } first(); // Output: Third, Second, First ``` ## The Event Loop 1. Execute all synchronous code 2. Push async callbacks to the message queue 3. When the stack is empty, run the next queue callback ```javascript console.log("1"); setTimeout(() => console.log("2"), 0); console.log("3"); // Output: 1, 3, 2 ``` ## Callbacks A function passed as an argument, executed later. ```javascript function fetchData(callback) { setTimeout(() => callback("Data received"), 1000); } fetchData((result) => { console.log(result); // "Data received" }); ``` ## setTimeout and setInterval ```javascript // One-time delay setTimeout(() => console.log("Hello"), 2000); // Repeating interval let count = 0; let id = setInterval(() => { console.log(`Count: ${count++}`); if (count >= 5) clearInterval(id); }, 1000); ``` **Tip:** Always clear `setInterval` when done to prevent memory leaks. ## Callback Hell Chaining callbacks creates deeply nested, hard-to-read code. ```javascript step1((err, result1) => { step2(result1, (err, result2) => { step3(result2, (err, result3) => { console.log(result3); }); }); }); ``` This is why Promises and `async/await` exist — they flatten the nesting. ## Best Practices - **Avoid deep nesting** — Use Promises or async/await - **Always handle errors** — Pass error as first callback argument - **Clear intervals** — Prevent memory leaks - **Keep callbacks small** — One thing per callback ## Common Mistakes - **Callback hell** — Nesting too deep - **Ignoring errors** — Not passing error in callbacks - **Assuming order** — Async callbacks may run out of order - **Forgetting to clear timers** — Memory leaks
No changes yet
Reset to original
Submit suggestion
cancel