Asynchronous JavaScript
1-Async Programming
Definition:
Asynchronous programming allows parts of your code to run in the background without
blocking the rest of the code.
Why it’s used:
To handle tasks that take time (e.g., timers, network requests) without freezing the UI.
Example JS:
[Link]("Start");
setTimeout(() => {
[Link]("I am asynchronous!");
}, 2000);
[Link]("End");
Line-by-line explanation:
1. [Link]("Start"); → prints "Start" immediately in the console.
2. setTimeout(() => { [Link]("I am asynchronous!"); }, 2000);
o setTimeout schedules a function to run after 2000 milliseconds (2 seconds).
o The function () => { [Link]("I am asynchronous!"); } is not
executed immediately, it’s placed in a timer queue.
3. [Link]("End"); → prints "End" immediately after "Start", before the
setTimeout callback executes.
4. After 2 seconds, the function inside setTimeout runs → prints "I am
asynchronous!".
Output order:
Start
End
I am asynchronous!
Lab 1 — Async Programming
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Async Programming Lab</title>
</head>
<body>
<h1>Async Programming Lab</h1>
<button id="btn">Click Me</button>
<p id="message">Message will appear here...</p>
<script>
const btn = [Link]("btn");
const message = [Link]("message");
[Link]("click", () => {
[Link] = "Waiting for 2 seconds...";
setTimeout(() => {
[Link] = "Done!";
}, 2000);
});
</script>
</body>
</html>
Limitations:
Only demonstrates asynchronous behavior; cannot handle complex sequences.
Why the next concept (setTimeout) was created:
To provide a simple way to delay a task execution.
2-setTimeout
Definition:
Executes a function once after a specific delay.
Why it’s used:
To delay tasks without blocking code execution.
Example JS:
[Link]("Before timeout");
setTimeout(() => {
[Link]("After 2 seconds");
}, 2000);
[Link]("Code continues...");
Line-by-line explanation:
1. [Link]("Before timeout"); → prints "Before timeout" immediately.
2. setTimeout(() => { [Link]("After 2 seconds"); }, 2000); →
schedules a function to run after 2 seconds.
o The arrow function () => { [Link]("After 2 seconds"); } is
stored in the timer and will execute later.
3. [Link]("Code continues..."); → prints "Code continues..."
immediately.
4. After 2 seconds → prints "After 2 seconds".
Lab 2 — setTimeout
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>setTimeout Lab</title>
</head>
<body>
<h1>setTimeout Lab</h1>
<button id="start">Start Timer</button>
<p id="status">Waiting...</p>
<script>
const startBtn = [Link]("start");
const status = [Link]("status");
[Link]("click", () => {
[Link] = "Timer started...";
setTimeout(() => {
[Link] = "2 seconds passed!";
}, 2000);
});
</script>
</body>
</html>
Limitations:
Only executes once, cannot repeat.
Hard to chain multiple delayed tasks → leads to callback hell.
Why the next concept (setInterval) was created:
To execute tasks repeatedly at fixed intervals.
3-setInterval
Definition:
Executes a function repeatedly at a set interval.
Why it’s used:
To perform repeated actions like counters, animations, or polling.
Example JS:
let count = 0;
const interval = setInterval(() => {
count++;
[Link]("Counter:", count);
if (count === 5) clearInterval(interval);
}, 1000);
Line-by-line explanation:
1. let count = 0; → declares a variable count starting at 0.
2. const interval = setInterval(..., 1000); → starts an interval timer that runs
every 1000ms (1 second).
3. count++; → increments the counter by 1 each time the interval executes.
4. [Link]("Counter:", count); → prints the current counter value.
5. if (count === 5) clearInterval(interval); → stops the interval after it
reaches 5.
Output: prints 1, 2, 3, 4, 5 every second.
Lab 3 — setInterval
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>setInterval Lab</title>
</head>
<body>
<h1>setInterval Lab</h1>
<button id="start">Start Counter</button>
<p id="counter">0</p>
<script>
const startBtn = [Link]("start");
const counterEl = [Link]("counter");
[Link]("click", () => {
let count = 0;
const interval = setInterval(() => {
count++;
[Link] = count;
if(count === 5) clearInterval(interval);
}, 1000);
});
</script>
</body>
</html>
Limitations:
Can drift if function execution takes longer than the interval.
Harder to handle errors or dependent sequences.
Why the next concept (Callback) was created:
To execute code after a task completes and handle sequences more clearly.
4-Callback
Definition:
A function passed as an argument to another function to be executed later.
Why it’s used:
To run code after a task finishes, e.g., after a timer or a data fetch.
Example JS:
function makeCoffee(callback) {
[Link]("Making coffee...");
setTimeout(() => {
[Link]("Coffee is ready!");
callback();
}, 2000);
}
makeCoffee(() => {
[Link]("Now I can drink it!");
});
Line-by-line explanation:
1. function makeCoffee(callback) { ... } → defines a function that takes another
function (callback) as input.
2. [Link]("Making coffee..."); → prints "Making coffee..." immediately.
3. setTimeout(() => { [Link]("Coffee is ready!"); callback(); },
2000);
o Waits 2 seconds, prints "Coffee is ready!"
o Calls the callback function passed to makeCoffee.
4. makeCoffee(() => { [Link]("Now I can drink it!"); });
o Calls makeCoffee, passing an anonymous function as callback.
o After 2 seconds, "Now I can drink it!" is printed.
Lab 4 — Callback (HTML + DOM)
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Callback Lab</title>
</head>
<body>
<h1>Callback Lab</h1>
<button id="start">Make Coffee</button>
<p id="status">Idle</p>
<script>
const startBtn = [Link]("start");
const status = [Link]("status");
function makeCoffee(callback) {
[Link] = "Making coffee...";
setTimeout(() => {
[Link] = "Coffee ready! ☕";
callback();
}, 2000);
}
[Link]("click", () => {
makeCoffee(() => {
[Link] += " → Now I can drink it!";
});
});
</script>
</body>
</html>
Limitations:
Leads to callback hell for multiple sequential tasks.
Harder to read and maintain.
Why the next concept (Promise) was created:
To provide a cleaner way to manage asynchronous sequences and errors.
5-Promise
Definition:
An object representing the future result of an asynchronous operation. States: pending,
fulfilled, rejected.
Why it’s used:
To handle asynchronous tasks without nesting multiple callbacks.
Example JS:
const promise = new Promise((resolve, reject) => {
setTimeout(() => resolve("Success!"), 2000);
});
[Link](result => [Link](result))
.catch(error => [Link](error));
Line-by-line explanation:
1. new Promise((resolve, reject) => { ... }); → creates a new Promise object.
2. setTimeout(() => resolve("Success!"), 2000); → after 2 seconds, the Promise
is resolved with "Success!".
3. [Link](result => [Link](result)) → runs when the Promise is
fulfilled, prints "Success!".
4. .catch(error => [Link](error)) → runs if the Promise is rejected (not
used in this example).
Lab 5 — Promise (HTML + DOM)
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Promise Lab</title>
</head>
<body>
<h1>Promise Lab</h1>
<button id="load">Load Data</button>
<p id="output">No data loaded</p>
<script>
const loadBtn = [Link]("load");
const output = [Link]("output");
function loadData() {
return new Promise(resolve => {
setTimeout(() => resolve({user: "Arnaud", age: 23}), 2000);
});
}
[Link]("click", () => {
[Link] = "Loading...";
loadData().then(data => {
[Link] = `User: ${[Link]}, Age: ${[Link]}`;
});
});
</script>
</body>
</html>
Limitations:
Chains of .then() can get long and hard to read.
Why the next concept (Async/Await) was created:
To write Promises in a synchronous-looking style for readability.
6-Async / Await
Definition:
Modern syntax that allows asynchronous code to look synchronous.
Why it’s used:
To simplify reading and writing asynchronous code.
Example JS:
async function task() {
[Link]("Start");
const result = await new Promise(resolve => setTimeout(() =>
resolve("Done!"), 2000));
[Link](result);
[Link]("End");
}
task();
Line-by-line explanation:
1. async function task() { ... } → declares an asynchronous function.
2. [Link]("Start"); → prints "Start" immediately.
3. await new Promise(...) → pauses execution inside the async function until the
Promise resolves.
4. [Link](result); → prints "Done!" after 2 seconds.
5. [Link]("End"); → prints "End" after the Promise resolves.
6. task(); → calls the async function.
Lab 6 — Async/Await (HTML + DOM)
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Async/Await Lab</title>
</head>
<body>
<h1>Async/Await Lab</h1>
<button id="load">Load Data</button>
<p id="output">No data yet</p>
<script>
const loadBtn = [Link]("load");
const output = [Link]("output");
function fetchData() {
return new Promise(resolve => {
setTimeout(() => resolve({user:"Arnaud", age:23}), 2000);
});
}
[Link]("click", async () => {
[Link] = "Loading...";
const data = await fetchData();
[Link] = `User: ${[Link]}, Age: ${[Link]}`;
});
</script>
</body>
</html>
Limitations:
Requires modern browsers (ES2017+).
Still asynchronous; blocking code inside await can slow UI if misused.
Why the next concept (fetch) was created:
To handle network requests cleanly in combination with Promises/Async-Await.
7️-Fetch API
Definition:
Fetches data from a server asynchronously and returns a Promise.
Why it’s used:
To retrieve JSON or other resources from APIs in a modern, readable way.
Example JS:
fetch("[Link]
.then(res => [Link]())
.then(data => [Link](data))
.catch(err => [Link](err));
Line-by-line explanation:
1. fetch(url) → requests data from the given URL. Returns a Promise.
2. .then(res => [Link]()) → converts the raw response into a JavaScript object.
3. .then(data => [Link](data)) → prints the JSON data.
4. .catch(err => [Link](err)) → prints an error if the request fails.
Lab 7 — Fetch API (HTML + DOM)
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Fetch Lab</title>
</head>
<body>
<h1>Fetch API Lab</h1>
<button id="fetchBtn">Fetch TODO</button>
<p id="result">No data</p>
<script>
const fetchBtn = [Link]("fetchBtn");
const result = [Link]("result");
[Link]("click", async () => {
[Link] = "Loading...";
try {
const response = await
fetch("[Link]
if(![Link]) throw new Error("HTTP error " + [Link]);
const data = await [Link]();
[Link] = `ID: ${[Link]}, Title: ${[Link]}`;
} catch(err) {
[Link] = "Error: " + err;
}
});
</script>
</body>
</html>
Limitations:
Only works in modern browsers (or needs polyfills for old ones).
Needs proper error handling ([Link]) for reliability.
Final lab
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Asynchronous JS Mega Lab</title>
<style>
body { font-family: Arial, sans-serif; margin: 20px; }
h1 { color: #2c3e50; }
section { border: 1px solid #ccc; padding: 15px; margin-bottom: 20px;
border-radius: 8px; }
button { margin-top: 10px; padding: 5px 10px; cursor: pointer; }
p { margin: 5px 0; }
</style>
</head>
<body>
<h1>🌟 Asynchronous JavaScript Mega Lab</h1>
<!-- 1️⃣ setTimeout -->
<section>
<h2>1️⃣ setTimeout</h2>
<p id="timeout-msg">Click "Start Timer" to run setTimeout</p>
<button id="timeout-btn">Start Timer</button>
<script>
const timeoutBtn = [Link]("timeout-btn");
const timeoutMsg = [Link]("timeout-msg");
[Link]("click", () => {
[Link] = "Timer started...";
setTimeout(() => {
[Link] = "2 seconds passed! ⏰";
}, 2000);
});
</script>
</section>
<!-- 2️⃣ setInterval -->
<section>
<h2>2️⃣ setInterval</h2>
<p id="interval-msg">Click "Start Counter" to run setInterval</p>
<button id="interval-btn">Start Counter</button>
<script>
const intervalBtn = [Link]("interval-btn");
const intervalMsg = [Link]("interval-msg");
[Link]("click", () => {
let count = 0;
[Link] = "Counter started...";
const interval = setInterval(() => {
count++;
[Link] = "Count: " + count;
if(count === 5) clearInterval(interval);
}, 1000);
});
</script>
</section>
<!-- 3️⃣ Callback -->
<section>
<h2>3️⃣ Callback</h2>
<p id="callback-msg">Click "Make Coffee" to run callback example</p>
<button id="callback-btn">Make Coffee</button>
<script>
const callbackBtn = [Link]("callback-btn");
const callbackMsg = [Link]("callback-msg");
function makeCoffee(callback) {
[Link] = "Making coffee...";
setTimeout(() => {
[Link] = "Coffee ready! ☕";
callback();
}, 2000);
}
[Link]("click", () => {
makeCoffee(() => {
[Link] += " → Now I can drink it!";
});
});
</script>
</section>
<!-- 4️⃣ Promise -->
<section>
<h2>4️⃣ Promise</h2>
<p id="promise-msg">Click "Load Data" to run Promise example</p>
<button id="promise-btn">Load Data</button>
<script>
const promiseBtn = [Link]("promise-btn");
const promiseMsg = [Link]("promise-msg");
function loadDataPromise() {
return new Promise(resolve => {
setTimeout(() => resolve({user: "Arnaud", age: 23}), 2000);
});
}
[Link]("click", () => {
[Link] = "Loading data...";
loadDataPromise().then(data => {
[Link] = `User: ${[Link]}, Age: ${[Link]}`;
});
});
</script>
</section>
<!-- 5️⃣ Async/Await -->
<section>
<h2>5️⃣ Async/Await</h2>
<p id="async-msg">Click "Fetch User" to run async/await example</p>
<button id="async-btn">Fetch User</button>
<script>
const asyncBtn = [Link]("async-btn");
const asyncMsg = [Link]("async-msg");
function fetchUser() {
return new Promise(resolve => {
setTimeout(() => resolve({name: "Therence", job: "Student"}), 2000);
});
}
[Link]("click", async () => {
[Link] = "Fetching user...";
const data = await fetchUser();
[Link] = `Name: ${[Link]}, Job: ${[Link]}`;
});
</script>
</section>
<!-- 6️⃣ Fetch API -->
<section>
<h2>6️⃣ Fetch API</h2>
<p id="fetch-msg">Click "Fetch TODO" to get data from server</p>
<button id="fetch-btn">Fetch TODO</button>
<script>
const fetchBtn = [Link]("fetch-btn");
const fetchMsg = [Link]("fetch-msg");
[Link]("click", async () => {
[Link] = "Fetching TODO...";
try {
const response = await
fetch("[Link]
if(![Link]) throw new Error("HTTP error " + [Link]);
const data = await [Link]();
[Link] = `ID: ${[Link]}, Title: ${[Link]}`;
} catch(err) {
[Link] = "Error: " + err;
}
});
</script>
</section>
</body>
</html>
Final lab 2
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>🌈 Asynchronous JS Mega Lab - Stylish Edition</title>
<style>
body {
font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
background: #f0f4f8;
margin: 0;
padding: 20px;
}
h1 {
text-align: center;
color: #2c3e50;
}
.container {
display: grid;
grid-template-columns: repeat(auto-fit, minmax(320px, 1fr));
gap: 20px;
margin-top: 20px;
}
.card {
background: white;
border-radius: 12px;
box-shadow: 0 4px 10px rgba(0,0,0,0.1);
padding: 20px;
transition: transform 0.2s;
}
.card:hover {
transform: scale(1.02);
}
h2 {
color: #34495e;
}
p {
margin: 10px 0;
min-height: 20px;
}
button {
background-color: #3498db;
color: white;
border: none;
padding: 8px 15px;
border-radius: 6px;
cursor: pointer;
font-weight: bold;
transition: background 0.2s;
}
button:hover {
background-color: #2980b9;
}
.output {
background: #ecf0f1;
padding: 10px;
border-radius: 6px;
font-family: monospace;
min-height: 25px;
}
</style>
</head>
<body>
<h1>🌈 Asynchronous JavaScript Mega Lab - Stylish Edition</h1>
<div class="container">
<!-- 1️⃣ setTimeout -->
<div class="card">
<h2>1️⃣ setTimeout</h2>
<p class="output" id="timeout-msg">Click "Start Timer"</p>
<button id="timeout-btn">Start Timer</button>
</div>
<!-- 2️⃣ setInterval -->
<div class="card">
<h2>2️⃣ setInterval</h2>
<p class="output" id="interval-msg">Click "Start Counter"</p>
<button id="interval-btn">Start Counter</button>
</div>
<!-- 3️⃣ Callback -->
<div class="card">
<h2>3️⃣ Callback</h2>
<p class="output" id="callback-msg">Click "Make Coffee"</p>
<button id="callback-btn">Make Coffee</button>
</div>
<!-- 4️⃣ Promise -->
<div class="card">
<h2>4️⃣ Promise</h2>
<p class="output" id="promise-msg">Click "Load Data"</p>
<button id="promise-btn">Load Data</button>
</div>
<!-- 5️⃣ Async/Await -->
<div class="card">
<h2>5️⃣ Async/Await</h2>
<p class="output" id="async-msg">Click "Fetch User"</p>
<button id="async-btn">Fetch User</button>
</div>
<!-- 6️⃣ Fetch API -->
<div class="card">
<h2>6️⃣ Fetch API</h2>
<p class="output" id="fetch-msg">Click "Fetch TODO"</p>
<button id="fetch-btn">Fetch TODO</button>
</div>
</div>
<script>
// 1️⃣ setTimeout
const timeoutBtn = [Link]("timeout-btn");
const timeoutMsg = [Link]("timeout-msg");
[Link]("click", () => {
[Link] = "Timer started...";
setTimeout(() => {
[Link] = "2 seconds passed! ⏰";
}, 2000);
});
// 2️⃣ setInterval
const intervalBtn = [Link]("interval-btn");
const intervalMsg = [Link]("interval-msg");
[Link]("click", () => {
let count = 0;
[Link] = "Counter started...";
const interval = setInterval(() => {
count++;
[Link] = "Count: " + count;
if(count === 5) clearInterval(interval);
}, 1000);
});
// 3️⃣ Callback
const callbackBtn = [Link]("callback-btn");
const callbackMsg = [Link]("callback-msg");
function makeCoffee(callback) {
[Link] = "Making coffee...";
setTimeout(() => {
[Link] = "Coffee ready! ☕";
callback();
}, 2000);
}
[Link]("click", () => {
makeCoffee(() => {
[Link] += " → Now I can drink it!";
});
});
// 4️⃣ Promise
const promiseBtn = [Link]("promise-btn");
const promiseMsg = [Link]("promise-msg");
function loadDataPromise() {
return new Promise(resolve => {
setTimeout(() => resolve({user: "Arnaud", age: 23}), 2000);
});
}
[Link]("click", () => {
[Link] = "Loading data...";
loadDataPromise().then(data => {
[Link] = `User: ${[Link]}, Age: ${[Link]}`;
});
});
// 5️⃣ Async/Await
const asyncBtn = [Link]("async-btn");
const asyncMsg = [Link]("async-msg");
function fetchUser() {
return new Promise(resolve => {
setTimeout(() => resolve({name: "Therence", job: "Student"}), 2000);
});
}
[Link]("click", async () => {
[Link] = "Fetching user...";
const data = await fetchUser();
[Link] = `Name: ${[Link]}, Job: ${[Link]}`;
});
// 6️⃣ Fetch API
const fetchBtn = [Link]("fetch-btn");
const fetchMsg = [Link]("fetch-msg");
[Link]("click", async () => {
[Link] = "Fetching TODO...";
try {
const response = await
fetch("[Link]
if(![Link]) throw new Error("HTTP error " + [Link]);
const data = await [Link]();
[Link] = `ID: ${[Link]}, Title: ${[Link]}`;
} catch(err) {
[Link] = "Error: " + err;
}
});
</script>
</body>
</html>