\n
\n
\n
Switch 12/24h \n\nCSS (ideas)\nā¤Big monospace font for time\nā¤Subtle gradient background\nā¤Center with Flexbox, add soft glow text-shadow\n\nJS (flow)\nā¤Keep a state: let is24 = false;\nā¤function updateClock() { \nconst now = new Date()\nGet hours/minutes/seconds\nā¤If 12-hour: hour = hour % 12 || 12 and add AM/PM\nā¤Format with a helper: pad(n) => n.toString().padStart(2,'0')\nā¤Build date string (e.g., Sunday, 17 September 2025)\nPut into #time and #date\n}\nā¤setInterval(updateClock, 1000); updateClock();\nOn toggle button click, flip is24 and re-render\nš” Hints\nArrays help format names: \nā„const days = [\"Sun\",\"Mon\",\"Tue\",\"Wed\",\"Thu\",\"Fri\",\"Sat\"];\nā„const months = [\"Jan\",\"Feb\",...,\"Dec\"];\nā„Use textContent to update DOM efficiently\nā„Use a single interval; donāt create multiple intervals on each click\n\nš£ Final Notes\n\nā
Keep your code clean: separate HTML structure, CSS styling, and JS behavior\nā
Test edge cases (empty display on =, multiple operators, midnight formats, etc.)\n\nShare your finished projects in the group, invite your friends, and as alwaysā\n\nĀ Ā Ā stay well, stay curious, and stay coding āļø","datePublished":"2025-08-26T15:20:20Z","dateModified":"2025-08-26T15:20:20Z","author":{"@type":"Organization","name":"Full Stack Camp","url":"https://telemetr.io/en/channels/2504967936-fullstackcampp","image":"https://img.tlmtr.io/c/2JwAAE/5999218308148218133?ty=x"},"publisher":{"@type":"Organization","name":"Full Stack Camp","url":"https://telemetr.io/en/channels/2504967936-fullstackcampp","image":"https://img.tlmtr.io/c/2JwAAE/5999218308148218133?ty=x"},"commentCount":0,"interactionStatistic":[{"@type":"InteractionCounter","interactionType":"https://schema.org/ViewAction","userInteractionCount":760},{"@type":"InteractionCounter","interactionType":"https://schema.org/ShareAction","userInteractionCount":7}]}},{"@type":"ListItem","position":17,"item":{"@type":"SocialMediaPosting","@id":"https://telemetr.io/en/channels/2504967936-fullstackcampp/posts/175","url":"https://telemetr.io/en/channels/2504967936-fullstackcampp/posts/175","mainEntityOfPage":"https://telemetr.io/en/channels/2504967936-fullstackcampp/posts/175","headline":"Assignment : ā¤Dom traverse https://youtu.be/RKXIMnSwUcg?si=FUKj1D4b7pC7XpFq ā¤currency https://youtu.be/HOMu48ā¦","articleBody":"Assignment :\nā¤Dom traverse \nhttps://youtu.be/RKXIMnSwUcg?si=FUKj1D4b7pC7XpFq\nā¤currency\nhttps://youtu.be/HOMu48bTzz8?si=rERc7uTzUX89twhi\nā¤console.time\nhttps://youtu.be/9amAW_qXv84?si=SA02eHAMPjKnn0Xf\nā¤date objects \nhttps://youtu.be/LwYwz67l1lA?si=BRjHz1NMzeaxuyvH\nā¤shuffle\nhttps://youtu.be/FGAUekwri1Q?si=HOUJ2olxK-PiBQNO\nā¤sorting \nhttps://youtu.be/CTHhlx25X-U?si=nW90hcx3kTpSKiuo\nā¤destructuring \nhttps://youtu.be/UHZcJyVXtLo?si=zpy9s31wdychlRm7","datePublished":"2025-08-26T15:19:24Z","dateModified":"2025-08-26T15:19:24Z","author":{"@type":"Organization","name":"Full Stack Camp","url":"https://telemetr.io/en/channels/2504967936-fullstackcampp","image":"https://img.tlmtr.io/c/2JwAAE/5999218308148218133?ty=x"},"publisher":{"@type":"Organization","name":"Full Stack Camp","url":"https://telemetr.io/en/channels/2504967936-fullstackcampp","image":"https://img.tlmtr.io/c/2JwAAE/5999218308148218133?ty=x"},"commentCount":0,"interactionStatistic":[{"@type":"InteractionCounter","interactionType":"https://schema.org/ViewAction","userInteractionCount":132}]}},{"@type":"ListItem","position":18,"item":{"@type":"SocialMediaPosting","@id":"https://telemetr.io/en/channels/2504967936-fullstackcampp/posts/174","url":"https://telemetr.io/en/channels/2504967936-fullstackcampp/posts/174","mainEntityOfPage":"https://telemetr.io/en/channels/2504967936-fullstackcampp/posts/174","headline":"š Intl.NumberFormat automatically localizes numbers & symbols. 7ļøā£ Measuring Code Speed with console.time Weā¦","articleBody":"š Intl.NumberFormat automatically localizes numbers & symbols.\n\n7ļøā£ Measuring Code Speed with console.time\n\nWe can measure how long a block of code takes to run.\n\nconsole.time(\"loop test\");\nlet sum = 0;\nfor (let i = 0; i < 1_000_000; i++) {\nĀ Ā Ā Ā sum += i; } \nconsole.timeEnd(\"loop test\"); \n// e.g. loop test: 12ms \nš Useful when comparing different ways of solving a problem.\nšÆ Wrap Up\nToday we learned:\nā How to move around HTML elements (DOM traversal)\nā Sorting & shuffling arrays (with destructuring explained first!)\nā Dates and how to format them\nā Currency formatting for real apps\nā Measuring performance with console.time\nā Cleaner code with destructuring\nEach of these may look small, but together they give you real-world tools youāll use in projects like calculators, dashboards, games, and even ecommerce apps.","datePublished":"2025-08-26T15:19:02Z","dateModified":"2025-08-26T15:19:02Z","author":{"@type":"Organization","name":"Full Stack Camp","url":"https://telemetr.io/en/channels/2504967936-fullstackcampp","image":"https://img.tlmtr.io/c/2JwAAE/5999218308148218133?ty=x"},"publisher":{"@type":"Organization","name":"Full Stack Camp","url":"https://telemetr.io/en/channels/2504967936-fullstackcampp","image":"https://img.tlmtr.io/c/2JwAAE/5999218308148218133?ty=x"},"commentCount":0,"interactionStatistic":[{"@type":"InteractionCounter","interactionType":"https://schema.org/ViewAction","userInteractionCount":102}]}},{"@type":"ListItem","position":19,"item":{"@type":"SocialMediaPosting","@id":"https://telemetr.io/en/channels/2504967936-fullstackcampp/posts/173","url":"https://telemetr.io/en/channels/2504967936-fullstackcampp/posts/173","mainEntityOfPage":"https://telemetr.io/en/channels/2504967936-fullstackcampp/posts/173","headline":"š Week 4 Day 9 ā DOM Traverse, Sort & Shuffle, Date, Currency, Console Time, Destructuring Hello Campers š, Fā¦","articleBody":"š Week 4 Day 9 ā DOM Traverse, Sort & Shuffle, Date, Currency, Console Time, Destructuring\n\nHello Campers š,\nFirst, big apology for the 3-day silence š. Sometimes life gets busy. Teaching is about consistency, and Iāll keep showing up with you. Today weāll break these topics into tiny bites with real-world meaning.\n\n1ļøā£ DOM Traversal (Walking around your HTML family tree)\n\nThink of your HTML as a family tree:\nā¤Parent = the container\nā¤Children = elements inside it\nā¤Siblings = brothers/sisters (elements at the same level)\nExample HTML:\n\n
\nĀ Ā Ā
Child 1
\nĀ Ā Ā
Child 2
\nĀ Ā Ā
Child 3
\n
\n\nJS Traversal:\n\nconst parent = document.getElementById(\"family\"); // Children (all kids) console.log(parent.children); // HTMLCollection \n\n// ā¤First & Last Child\nconsole.log(parent.firstElementChild.textContent); // \"Child 1\" console.log(parent.lastElementChild.textContent); // \"Child 3\" \n\n// ā¤Parent of Child 2\nlet child2 = parent.children[1]; console.log(child2.parentElement.id); // \"family\"\n\n//⤠Siblings\nconsole.log(child2.previousElementSibling.textContent); // \"Child 1\"\nconsole.log(child2.nextElementSibling.textContent); // \"Child 3\" \n\nš This is how we move around the DOM when we need not just one element but relationships.\n\n2ļøā£ Sorting Arrays\nSorting means arranging data in order (alphabetical, numeric, etc.).\nExample: sorting numbers\n\nlet scores = [40, 100, 1, 5, 25, 10]; \n\n// Wrong (default = alphabetical!) console.log(scores.sort()); // [1, 10, 100, 25, 40, 5]\n\n// Correct numeric sort \nscores.sort((a, b) => a - b);\nconsole.log(scores); // [1, 5, 10, 25, 40, 100] \n\n// Descending\nscores.sort((a, b) => b - a);\nconsole.log(scores); // [100, 40, 25, 10, 5, 1] \nš Always pass a compare function when sorting numbers.\n\n3ļøā£ Destructuring (Unpacking values quickly)\n\nThis is like saying:\nāInstead of carrying a whole bag, let me just pull out the items I need.ā\nArrays:\n\nlet colors = [\"red\", \"green\", \"blue\"]; \n\n// Without destructuring: \nlet first = colors[0];\nlet second = colors[1];\n\n// With destructuring:\nlet [c1, c2, c3] = colors;\nconsole.log(c1); // red\nconsole.log(c2); // green\nconsole.log(c3); // blue \n\nObjects:\n\nlet student = { name: \"Amina\", age: 20, city: \"Addis\" }; \n\n// Without destructuring:\nlet n = student.name;\nlet c = student.city; \n\n// With destructuring: \nlet { name, city } = student;\nconsole.log(name); // Amina\nconsole.log(city); // Addis\n\n\nš Weāll now use this in shuffling to make swaps shorter.\n\n4ļøā£ Shuffle Arrays (Randomize order)\n\nImagine shuffling cards in a game. We can randomize an array using the Fisher-Yates method.\n\nlet students = [\"Aman\", \"Lily\", \"Sara\", \"Kebede\", \"Muna\"]; \nfor (let i = students.length - 1; i > 0; i--) {\nĀ Ā Ā Ā let j = Math.floor(Math.random() * (i + 1));\n// Swap students[i] with students[j]\nĀ Ā [students[i], students[j]] = [students[j], students[i]]; // destructuring swap }\nconsole.log(students); \n\nš Thanks to destructuring, swapping values looks neat: [a, b] = [b, a];\n\n5ļøā£ Dates (Working with real-world time)\n\nThe Date object lets us work with todayās time.\n\nlet now = new Date();\nconsole.log(now); // full date & time\nconsole.log(now.getFullYear()); // year\nconsole.log(now.getMonth()); // 0-11 (0 = January)\nconsole.log(now.getDate()); // day of month\nconsole.log(now.getDay()); // 0-6 (0 = Sunday)\nconsole.log(now.getHours()); // hour\nconsole.log(now.toDateString()); // \"Tue Aug 26 2025\"\nconsole.log(now.toLocaleString()); // local format \n\nš Note: months start at 0.\n\n6ļøā£ Currency Formatting\n\nWhen showing money, we need proper formatting.\n\nlet price = 12345.678; \n// USD\nconsole.log( new Intl.NumberFormat(\"en-US\", { style: \"currency\", currency: \"USD\" }).format(price) ); // $12,345.68\n\n// Ethiopian Birr\nconsole.log( new Intl.NumberFormat(\"am-ET\", { style: \"currency\", currency: \"ETB\" }).format(price) ); // Br 12,345.68","datePublished":"2025-08-26T15:18:46Z","dateModified":"2025-08-26T15:18:46Z","author":{"@type":"Organization","name":"Full Stack Camp","url":"https://telemetr.io/en/channels/2504967936-fullstackcampp","image":"https://img.tlmtr.io/c/2JwAAE/5999218308148218133?ty=x"},"publisher":{"@type":"Organization","name":"Full Stack Camp","url":"https://telemetr.io/en/channels/2504967936-fullstackcampp","image":"https://img.tlmtr.io/c/2JwAAE/5999218308148218133?ty=x"},"commentCount":0,"interactionStatistic":[{"@type":"InteractionCounter","interactionType":"https://schema.org/ViewAction","userInteractionCount":100}]}},{"@type":"ListItem","position":20,"item":{"@type":"SocialMediaPosting","@id":"https://telemetr.io/en/channels/2504967936-fullstackcampp/posts/172","url":"https://telemetr.io/en/channels/2504967936-fullstackcampp/posts/172","mainEntityOfPage":"https://telemetr.io/en/channels/2504967936-fullstackcampp/posts/172","headline":"Want to study C++ or Python? My friendās channel on YouTube uses great examples to make things easy to undersā¦","articleBody":"Want to study C++ or Python? My friendās channel on YouTube uses great examples to make things easy to understandātake a look and subscribe.\n\nhttps://youtube.com/@twohmschool?si=FuOAaJnKzW_WXtvZ","datePublished":"2025-08-24T17:12:07Z","dateModified":"2025-08-24T17:12:07Z","author":{"@type":"Organization","name":"Full Stack Camp","url":"https://telemetr.io/en/channels/2504967936-fullstackcampp","image":"https://img.tlmtr.io/c/2JwAAE/5999218308148218133?ty=x"},"publisher":{"@type":"Organization","name":"Full Stack Camp","url":"https://telemetr.io/en/channels/2504967936-fullstackcampp","image":"https://img.tlmtr.io/c/2JwAAE/5999218308148218133?ty=x"},"commentCount":0,"interactionStatistic":[{"@type":"InteractionCounter","interactionType":"https://schema.org/ViewAction","userInteractionCount":120},{"@type":"InteractionCounter","interactionType":"https://schema.org/ShareAction","userInteractionCount":1}]}}]}
š Week 5 Day 3 Challenges ā Promises
Time to put our Promises knowledge into action with some exciting real-world flavored challenges! š»āØ
1ļøā£ Profile Picture Loader š¤
š Simulate a Promise that ādownloadsā a profile picture after 2 seconds. When itās done, log "Profile picture loaded!".
š” Hint : Wrap setTimeout inside a Promise and resolve it with the message.
2ļøā£ Online Exam Timer ā³
š Use Promises to simulate a countdown:
"Exam starting in 3..."
"2..."
"1..."
"Start now!"
š” Hint : Chain Promises with different delays.
3ļøā£ Banking Transaction š³
š Build a Promise that:
Resolves with "Transaction successful" if account balance ā„ withdrawal amount
Rejects with "Insufficient funds" otherwise
š” Hint : Pass balance and amount as parameters.
4ļøā£ News Fetcher š°
š Make three Promises that each resolve with "News 1", "News 2", "News 3" after different times. Use Promise.all() to display all news when ready.
š„ These four challenges are like mini stepping-stones into the real world of async tasks. Take your time, break them down, and remember: coding is all about practice and patience .
š„ share your solutions in the group,
š„invite a friend,
and as always ā
š„stay well, stay curious, and stay coding āļø
š„ Extra Promise Examples
1ļøā£ Delayed Message Example
Imagine you want to show a greeting after 3 seconds.
function delayedMessage(msg, time) {
return new Promise(resolve => {
setTimeout(() => { resolve(msg); }, time); }); }
delayedMessage("š Hello campers!", 3000)
.then(res => console.log(res));

š
Explanation :
delayedMessage() returns a Promise.
After time (3000ms = 3s), the message is resolved.
.then() receives the final value and logs it.
2ļøā£ Random Weather Reporter
Letās pretend weāre building a weather service š¦ļø
function getWeather() { return new Promise((resolve, reject) => {
let weather = ["āļø Sunny", "š§ļø Rainy", "ā
Cloudy"];
let random = Math.random();
if (random > 0.2) { resolve(weather[Math.floor(Math.random() * weather.length)]); }
else { reject("ā Weather service unavailable"); } }); }
getWeather()
.then(res => console.log("Todayās weather:", res))
.catch(err => console.log(err));
š
Explanation :
ā¤80% chance to get a random weather report.
ā¤20% chance to reject with an error.
ā¤Shows how Promises handle both
success and
failure cases.
3ļøā£ Promise Chaining: Coffee Order ā
You order coffee ā they prepare ā they deliver.
function orderCoffee() { return new Promise(resolve => {
resolve("ā
Order placed"); }); }
orderCoffee()
.then(msg => {
console.log(msg);
return "ā Coffee is being prepared"; })
.then(msg => {
console.log(msg);
return "š Coffee is on the way"; })
.then(msg => {
console.log(msg);
return "š Coffee delivered!"; })
.then(final => console.log(final));
š
Explanation :
Each .then() returns a new value ā passed to the next .then().
Itās like following steps in
real-world tasks .
4ļøā£ Simulating an Online Exam Result š
function checkResult(score) { return new Promise((resolve, reject) => {
if (score >= 50) { resolve("š You passed with " + score + "%"); }
else { reject("ā You failed with " + score + "%"); } }); }
checkResult(72)
.then(res => console.log(res))
.catch(err => console.log(err));

š
Explanation :
ā¤If the score is 50 or above ā Promise resolves.
ā¤Otherwise ā Promise rejects.
A simple way to show
yes/no outcomes .
5ļøā£ Running Multiple Promises Together
Promise.all()
Wait for
all tasks to finish.
let promise1 = new Promise(resolve => setTimeout(() => resolve("ā
Task 1 done"), 1000));
let promise2 = new Promise(resolve => setTimeout(() => resolve("ā
Task 2 done"), 2000));
Promise.all([promise1, promise2])
.then(results => console.log("All tasks finished:", results));
š
Explanation :
ā¤Promise.all() waits until
all promises are resolved .
ā¤Returns an array of results.
Promise.race()
Who finishes first? š
let fast = new Promise(resolve => setTimeout(() => resolve("ā” Fast task finished"), 1000));
let slow = new Promise(resolve => setTimeout(() => resolve("š¢ Slow task finished"), 3000));
Promise.race([fast, slow])
.then(result => console.log(result));

š
Explanation :
ā¤Promise.race() returns the result of the
first resolved promise .
Great analogy: runners in a race.
ā
With these
extra examples , you can see how Promises:
ā¤Delay things (timers)
ā¤Represent real-world uncertain tasks (weather, exam results)
ā¤Can chain steps (coffee order)
ā¤Can run multiple tasks together (all, race)
𤯠Why Promises?
ā¤Before Promises, developers had to use
nested callbacks (callback hell). ā¤Promises clean that mess and make code more readable and maintainable.
Instead of:
task1(() => {
task2(() => {
task3(() => { console.log("Done!"); }); }); });
We can write:
task1()
.then(task2)
.then(task3)
.then(() => console.log("Done!"))
.catch(err => console.log(err));
Much cleaner ā
š” Summary
ā
A
Promise represents a future result of an asynchronous task.
ā
It can be
pending ,
fulfilled , or
rejected .
ā
Use .then() for success and .catch() for errors.
ā
Promises can be chained for sequential tasks.
ā
They help us avoid messy
callback hell .
š Week 5 Day 3 ā Promises in JavaScript
Hello Campers! šāØ
I hope youāre doing amazing and coding strong. Today, we step into one of the
most powerful and practical features of JavaScript :
Promises .
This lesson is so important because almost everything in modern JavaScriptālike fetching data from an API, loading files, connecting to a database, or working with timersādepends on
Promises .
So letās slow down, break it piece by piece, and understand them deeply.
š What is a Promise? (Big Picture)
š A
Promise in JavaScript is like a
commitment someone makes to you:
ā¤Your friend says:
āIāll bring you injera tomorrow.ā
Thatās a
promise . Right now, you donāt have the injera, but you expect to get it.
While waiting, there are
three possible outcomes :
š”
Pending ā Your friend hasnāt arrived yet (youāre still waiting).
š¢
Fulfilled ā Your friend arrives with injera ā
(promise kept).
š“
Rejected ā Your friend couldnāt bring it ā (promise broken).
This is exactly how JavaScript handles asynchronous tasks. A
Promise is just an object that tells you:
āI might not be ready yet, but Iāll either succeed or fail in the future.ā
š Promise States
ā
Pending ā Task is still running, nothing decided yet.
ā
Fulfilled (Resolved) ā Task completed successfully, and we have a value.
ā
Rejected ā Task failed, and we have a reason (error).
š ļø How to Create a Promise
let myPromise = new Promise((resolve, reject) => {
let success = true;
if (success) { resolve("š Task completed successfully!"); }
else { reject("ā Something went wrong!");
} });
š Explanation:
ā¤resolve() is called if the promise succeeds.
ā¤reject() is called if it fails.
ā¤But just creating a promise does nothing. We need to
use it.
š¦ Consuming a Promise
We use .then() and .catch() to handle the outcomes.
myPromise .then(result => {
console.log(result); // š Task completed successfully! })
.catch(error => { console.log(error); // ā Something went wrong! });
š Think of .then() as:
āWhat should I do if my friend keeps their promise?ā
š .catch() is:
āWhat should I do if my friend breaks the promise?ā
š² Real-World Analogy: Restaurant Order
Imagine you order
shiro at a restaurant.
ā¤You place the order ā
Promise created (pending).
ā¤If the chef prepares it ā
resolve() (fulfilled).
ā¤If the restaurant runs out of shiro ā
reject() (rejected).
ā¤You (the customer) wait. When itās ready, the waiter calls you ā thatās .then().
ā¤If they say
āSorry, no shiroā ā thatās .catch().
š Promise Chaining
You can link multiple .then() calls together, where the output of one becomes the input of the next.
let step1 = new Promise((resolve, reject) => {
resolve(2); });
step1 .then(num => {
console.log("First result:", num);
return num * 2; // Passes 4 to next then })
.then(num => {
console.log("Second result:", num);
return num * 3; // Passes 12 to next then })
.then(num => {
console.log("Final result:", num); // 12 });
š Promise chaining is like following steps in a recipe. Each step transforms the result and passes it to the next.
š Handling Errors
let riskyTask = new Promise((resolve, reject) => {
let value = Math.random();
if (value > 0.5) { resolve("ā
Success! Value: " + value); }
else { reject("ā Failure! Value: " + value); } });
riskyTask
.then(res => console.log(res))
.catch(err => console.log(err));

š Even if you chain multiple .then() calls, a single .catch() at the end can handle all errors in the chain.
ā³ Using Promises with setTimeout (Demo)
function wait(ms) { return new Promise(resolve => {
setTimeout(() => { resolve(Waited ${ms} milliseconds); }, ms);
}); }
wait(2000).then(message => console.log(message));
š This code waits
2 seconds , then prints:
Waited 2000 milliseconds
Itās like telling JavaScript:
āPause for 2 seconds, then let me know.ā š„ Reality Check for Beginner Coders š„
Listenāwatching 100 YouTube tutorials wonāt make you a coder.
Writing one small messy project will teach you more than all those videos combined.
Stop fooling yourself with āIāll start after I finish this tutorialā or āI need to know everything first.ā
Youāll never know everything. And you donāt need to.
š” Build something small . A calculator. A to-do list. A digital clock.
It wonāt be perfectāgood. It doesnāt have to be. Coding isnāt about perfection, itās about consistency .
Donāt make 10 big plans a day and execute none. Make 1 simple plan and show up for it every day.
Consistency beats motivation. Consistency beats talent.
And when you get stuck? Ask. Even if your question feels ādumb.ā The dumb question you ask today is the breakthrough you needed yesterday.
Mistakes? Youāll make tons. Thatās how you learn . Every bug you fight, every error you fix, becomes knowledge youāll never forget .
Hereās the raw truth:
⨠No mentor, no tutorial, no friend can carry your dream. Itās you. Only you.
If you want it, you fight for it. You sit, you code, you fail, you repeat.
Because in the endāyour future, your dream, your freedomāisnāt waiting on YouTube.
Itās waiting on your hands to type that first line of code.
ā” Stop hiding. Start building. Even the smallest project is a step toward the life you want. ā”
š„ Week 5 Day 2 ā Async Callback Challenges
Hey Campers š, you did great today learning about callbacks in async tasks (like setTimeout & setInterval) and also about the infamous Callback Hell š.
Now itās time to practice! Here are 4 challenge ideas .
1. Delayed Welcome Message
š Write a function that shows "Welcome Camper!" after 3 seconds using setTimeout.
š” Hint: Wrap your console.log inside a setTimeout.
2. Simple Digital Timer
š Build a timer that counts up from 0 seconds and displays it in the console every second. Stop it after 10 seconds .
š” Hint: Use setInterval to keep counting, and clearInterval to stop it.
3. Countdown Launcher š
š Create a countdown starting from 5 down to 1 , then finally log "Blast off!".
š” Hint: setInterval works well here, but make sure to stop it at the right time.
4. Sequential Messages
š Show these messages in order with delays:
After 1s ā "Preparing..."
After 3s ā "Loading..."
After 5s ā "Ready!"
š” Hint: Use multiple setTimeout calls ā this will give you a taste of callback hell ! š
š Donāt forget to
š„ share your solutions in the group,
š„invite a friend ,
and as always ā
š„stay well, stay curious, and stay coding āļø
5) Callback Hell (the āPyramid of Doomā)
When async steps depend on each other and you keep
nesting callbacks inside callbacks , your code can become hard to read, test, and maintain.
Example: three steps in order (bad nesting)
setTimeout(() => {
console.log("Step 1");
setTimeout(() => {
console.log("Step 2");
setTimeout(() => {
console.log("Step 3"); // keep going... šµ }, 1000);
}, 1000);
}, 1000);
Problems:
ā¤Hard to
read (moves to the right like a pyramid)
ā¤Hard to
handle errors
ā¤Hard to
reuse parts
How to reduce the pain (without Promises yet)
A) Use named functions (flatten the shape):
function step1() {
console.log("Step 1");
setTimeout(step2, 1000); }
function step2() {
console.log("Step 2");
setTimeout(step3, 1000); }
function step3() {
console.log("Step 3"); }
setTimeout(step1, 1000);
B) Self-scheduling pattern (recursion style):
function runStep(n, max) {
if (n > max) return; console.log("Step", n);
setTimeout(() => runStep(n + 1, max), 1000); }
runStep(1, 3);
Next lessons will fix this elegantly with
Promises and
async/await (much cleaner than deep nesting).
6) setInterval vs ārecursiveā setTimeout
setInterval(fn, 1000) tries to run every 1000ms. If fn takes long, calls can bunch up or drift.
A safer approach for consistent spacing is
self-scheduling :
function tick() {
console.log(new Date().toLocaleTimeString());
setTimeout(tick, 1000); // schedule the next tick after this finishes }
tick();
This avoids overlapping calls and adapts to work time.
7) Common mistakes & best practices
ā
Store timer IDs (const id = setTimeout(...);) if you might cancel them.
ā
Clean up intervals with clearInterval(id) when youāre done (avoid āzombieā timers).
ā
Keep callbacks
small and
named where possible (easier to debug).
ā ļø Donāt assume the exact delay; the
event loop controls when callbacks actually run.
ā ļø Avoid deep nesting ā prefer named functions or (soon)
Promises / async-await .
8) Tiny utility helpers
ā¤
Leading zeros (e.g., 09:05:03):
const pad2 = (n) => String(n).padStart(2, "0");
ā¤
Debounce concept (preview) ā wait until the user stops typing:
function debounce(fn, delay) {
let id;
return (...args) => {
clearTimeout(id);
id = setTimeout(() => fn(...args), delay); }; } // Usage later with input events
(Youāll use this a lot when we reach real search boxes and forms.)
Recap
ā
Callback = a function to run
later .
ā
setTimeout ā run
once after a delay; ā
clearTimeout to cancel.
ā
setInterval ā run
repeatedly ; ā
clearInterval to stop.
ā
Callback hell happens with deep nestingāfight it with
named functions or the
self-scheduling pattern (and soon with Promises/async-await).
ā
Real-world uses: delayed messages, countdowns, clocks, stopwatches, reminders.
Thatās todayās deep dive šŖ. Next up:
Promises āa cleaner, more powerful way to write async code (goodbye pyramid of doom).
š Week 5 Day 2 ā Callbacks in Async (setTimeout, setInterval)
š
Hello Campers!
Ready for day 2 of async JavaScript? Yesterday we built the
mindset (single-threaded JS, event loop). Today weāll use two core async toolsāsetTimeout and setIntervalāand learn what a
callback really is, why ā
callback hell ā happens, and how to avoid it. Weāll end with small, real-world demos (delayed messages + simple timers). Letās go. š
1) What is a callback?
A
callback is just a
function you pass to another function so it can be called
later (when something is ready).
ā
Sync callback (runs immediately):
[1, 2, 3].forEach(function (n) { console.log(n); // runs now, during forEach });
ā
Async callback (runs later):
setTimeout(function () { console.log("Runs after 1000ms"); }, 1000);
Analogy: you give a cafƩ your phone number (callback). When the coffee is ready (async), they call you back.
2) setTimeout ā run once after a delay
Syntax
const timerId = setTimeout(callback, delayMs, arg1, arg2, ...);
ā¤callback: function to run later
ā¤delayMs: delay in milliseconds
ā¤returns a
timer ID (so you can cancel)
Basic examples
setTimeout(() => { console.log("Hello after 2 seconds"); }, 2000); // Passing data to the callback function
greet(name) { console.log(Hi, ${name}!); }
setTimeout(greet, 1500, "Muna"); // "Hi, Muna!" after 1.5s
Cancel a scheduled timeout
const id = setTimeout(() => console.log("This will never run"), 3000);
clearTimeout(id);
Important notes
The delay is
minimum time. The callback runs
as soon as the call stack is free (event loop).
Always
save the timer ID if you might cancel it.
3) setInterval ā run repeatedly every N ms
Syntax
const intervalId = setInterval(callback, intervalMs, arg1, arg2, ...);
Basic example
const id = setInterval(() => { console.log(new Date().toLocaleTimeString()); }, 1000); // Stop after 5 seconds
setTimeout(() => clearInterval(id), 5000);
Cancel a repeating interval
clearInterval(intervalId);
Caution
Intervals can ādriftā a little (not perfectly on time). For critical timing, prefer a
self-scheduling timeout .
4) Real-world mini demos
A) Delayed welcome message (one-time setTimeout)
<div id="msg" style="display:none; padding:8px; background:#eef;"> Welcome back! š </div>
<script>
const msg = document.getElementById("msg"); // Show after 1.5 seconds
const showId = setTimeout(() => { msg.style.display = "block"; // Hide again after 3 seconds
setTimeout(() => (msg.style.display = "none"), 3000); }, 1500);
</script>
B) Simple countdown (with setInterval)
let seconds = 5;
const id = setInterval(() => {
console.log(seconds);
if (seconds === 0) { console.log("Go! š");
clearInterval(id); }
seconds--; }, 1000);
C) Stopwatch (start/stop/reset) ā self-contained logic
<div>
<div id="time" style="font: 24px monospace;">00:00.0</div>
<button id="start">Start</button>
<button id="stop">Stop</button>
<button id="reset">Reset</button>
</div>
<script>
const timeEl = document.getElementById("time");
const startBtn = document.getElementById("start");
const stopBtn = document.getElementById("stop");
const resetBtn = document.getElementById("reset");
let startAt = null; // timestamp when started
let tickId = null; // interval ID
function format(ms) { const total = Math.floor(ms / 100);
const mm = String(Math.floor(total / 600)).padStart(2, "0"); // minutes
const ss = String(Math.floor((total % 600) / 10)).padStart(2, "0"); // seconds
const t = total % 10; // tenths
return ${mm}:${ss}.${t}; }
function update() {
const elapsed = Date.now () - startAt;
timeEl.textContent = format(elapsed); }
startBtn.onclick = () => { if (tickId) return; // already running
startAt = Date.now () - (parseFloat(timeEl.textContent.replace(/[:.]/g,'')) || 0);
tickId = setInterval(update, 100); // update every 100ms };
stopBtn.onclick = () => { clearInterval(tickId); tickId = null; };
resetBtn.onclick = () => { clearInterval(tickId); tickId = null; timeEl.textContent = "00:00.0"; };
</script> š Week 5 Day 1 ā Asynchronous JS Reading Challenge
Goal: Make sure you really understand what async is, why it exists, and how JS handles tasks in the background .
š¹ Part 1: Quick Questions
Answer these without looking back at the lesson first ā test your memory and understanding.Explain in your own words:
1.Whatās the difference between synchronous and asynchronous code?
2.Imagine youāre in a cafĆ©:
ā„Which part of the coffee process is like the Call Stack ?
ā„Which part is like the Web API / background task ?
ā„Which part is like the Callback Queue ?
ā„Who is the Event Loop in this analogy?
3.Why would a JavaScript web page freeze if we didnāt use asynchronous code?
4.List 2 examples of asynchronous functions in JS and explain what they do.
š¹ Part 2: True or False
1,setTimeout blocks the rest of your code until it finishes.
2,JavaScript can do multiple things at the exact same time on its main thread.
3,Asynchronous code helps make apps faster and smoother .
4,The Event Loop checks if the Call Stack is empty before moving tasks from the Callback Queue.
š¹ Part 3: Scenario Thinking
Read the scenarios and explain what will happen first :
1.You order coffee ā (takes 3 minutes), start talking to a friend, and the waiter brings your coffee when ready.
Which happens first: talking to a friend or getting coffee?
2.You request data from a server using fetch(). While waiting, you click a button that opens a popup.
Will the popup wait for the data to finish downloading, or appear immediately?
3.You use setTimeout for 5 seconds to show a message, but in the meantime, you print āHelloā to the console.
What gets logged first: āHelloā or the 5-second message?
š¹ Part 4: Reflection
Write 2ā3 sentences about why you think asynchronous programming is important for real websites and apps . Use examples from Google, Instagram, or YouTube.
Donāt forget to
š„š„ share your solutions,
š„š„invite your friends,
and as alwaysā¦
š„š„āļøāļøstay well, stay curious, and stay coding āļø
š Week 5 Day 1 ā Introduction to Asynchronous JavaScript
š
Hello Campers!
Welcome to
Week 5 of our
Fullstack Summer Camp ! Weāve been doing an amazing job so far ā from variables and functions, all the way to DOM and OOP. Today, we are stepping into one of the most important (and a bit tricky) parts of JavaScript:
Asynchronous Programming .
Donāt worry ā weāll take it step by step, with simple words, good analogies, and examples.
š 1. First, What Does "Asynchronous" Mean?
Synchronous = things happen
one after the other .
Example: You stand in line to buy
injera š„. Each person must finish buying before the next can order.
Asynchronous = things can happen
while waiting .
Example: You order coffee ā at a cafĆ©. The waiter tells you to sit, and while the coffee is being prepared, you can check your phone, talk to a friend, or do homework. You donāt need to stand stuck until itās ready.
š Thatās what
JavaScript does : it allows some tasks to happen in the background (like waiting for data, downloading files, or timers) while the rest of the code keeps running.
š§µ 2. Why Do We Need Async in JavaScript?
JavaScript is
single-threaded ā it can only do one thing at a time. If we write blocking code (like waiting 5 seconds), the whole page will freeze š³.
Imagine:
You open a website.
The website tries to
download a 5MB image .
If JavaScript was synchronous only, the entire page would stop until the image finished downloading. No scrolling, no clicking, nothing.
Asynchronous programming
fixes this ā it lets JS say:
š āOkay, Iāll start downloading this, but meanwhile, let me keep running the rest of the code. Iāll come back when the download is ready.ā
š 3. The Event Loop ā JavaScriptās Coffee Shop ā
Hereās the magic of how async works:
ā¤
Call Stack ā where JavaScript runs your main code (line by line).
ā¤
Web APIs / Background tasks ā where timers, fetch requests, etc., wait.
ā¤
Callback Queue ā when those tasks are finished, they move here.
ā¤
Event Loop ā a helper that checks: āIs the stack empty? If yes, Iāll take a task from the queue and run it.ā
š Analogy:
Think of a
coffee shop :
ā¤The cashier = Call Stack (takes orders).
ā¤The barista = Web API (prepares coffee in the back).
ā¤The pick-up counter = Callback Queue (finished coffees waiting).
ā¤The waiter = Event Loop (delivers coffee when the cashier is free).
So, JS can keep ātaking ordersā while some work happens in the background.
š» 4. Examples of Synchronous vs Asynchronous
Example 1: Synchronous
console.log("1. Order injera");
console.log("2. Wait until injera is ready");
console.log("3. Eat injera");
Output (always in order):
1. Order injera
2. Wait until injera is ready
3. Eat injera
Everything waits for the previous step.
Example 2: Asynchronous with setTimeout
console.log("1. Order coffee");
setTimeout(() => { console.log("2. Coffee is ready!"); }, 2000);
console.log("3. Talk with friend");
Output:
1. Order coffee
3. Talk with friend
2. Coffee is ready!
š Notice: āTalk with friendā runs
before coffee is ready. Thatās async!
š§ 5. Common Asynchronous Functions in JS
ā¤
setTimeout() ā run code after some delay.
ā¤
setInterval() ā run code repeatedly after a time gap.
ā¤
fetch() ā get data from a server (weāll learn in detail later).
ā¤
Event listeners ā e.g., when user clicks, the function is called later.
All these donāt block the code ā they run in the background and ācome backā when ready.
š 6. Real-World Examples
ā¤When you type in Google search ā results load
without reloading the whole page (async API calls).
ā¤When you scroll Instagram ā new posts load in the background.
ā¤When you press play on YouTube ā video streams while comments load separately.
š Key Takeaways
ā¤JavaScript is
single-threaded (one main line of execution).
ā¤To avoid blocking, it uses
asynchronous programming .
ā¤Async tasks (timers, requests, events) go to the
Web APIs ā then return later via the
Event Loop .
ā¤Async = smoother, faster, more user-friendly apps.
challenges of week 4.zip 1.17 MB
Where do you currently stand on this?
Anonymous voting š Project 1: Calculator & Digital Clock
Hello Campers š
I know we still haven't finished JavaScript , but it's time to use what we have learned so far for two real mini-apps. Using google is allowed, but make sure you understand every line of code.
1) š§® Calculator (Basic ā Plus)
ā
What to build
A clean on-page calculator with:
ā¤Display screen
ā¤Buttons: 0ā9, + - Ć Ć·, . (decimal), =, C (clear), ā (backspace)
š§© Core features
ā¤Click buttons to show numbers/operators on the display
ā¤= evaluates the expression and shows the result
ā¤C clears everything, ā removes last character
ā¤Prevent invalid inputs (e.g., two operators in a row)
š ļø Suggested structure
ā
HTML
ā¶ļø<div class="calc"> with a <input id="display" readonly>
ā¶ļøA grid of <button>s for digits/operators
ā
CSS (ideas)
ā¶ļøUse CSS Grid for the buttons
ā¶ļø:hover and :active styles for click feedback
ā¶ļøBigger font for display, subtle shadow for the calculator body
ā
JS (flow)
ā¶ļøGrab all buttons and the display (document.getElementById, querySelectorAll)
ā¶ļøOn button click, update display.value
ā¶ļøOn =, safely evaluate (donāt use raw eval in real apps; for now you can map Ćā*, Ć·ā/ and evaluate using Function or a simple parser)
ā¶ļøOn C, set display.value = ''
ā¶ļøOn ā, remove last char:
ā¶ļødisplay.value = display.value.slice(0, -1)
āŖļøEdge cases: avoid .. twice, avoid ++, --, **, //, and starting with an operator (except minus if you want negative numbers)
š” Hints
ā„Keep allowed chars list: digits 0ā9, ., + - * /
ā„Replace visual operators before evaluation: ā„input.replaceAll('Ć','*').replaceAll('Ć·','/')
ā„Disable multiple operators in a row by checking the last character before appending
ā„Optional: add keyboard support with keydown events
2) ā° Digital Clock (Live Time + Options)
ā
What to build
A live clock that updates every second:
Hours:Minutes:Seconds
AM/PM (12-hour) and 24-hour toggle
Day and date display
š§© Core features
ā¤Show current time (HH:MM:SS)
ā¤Update every 1000 ms with setInterval
Format leading zeros (e.g., 09:05:03)
ā¤Show day name and full date
š ļø Suggested structure
HTML
<div class="clock">
<div id="time"></div>
<div id="date"></div>
<button id="toggleFormat">Switch 12/24h</button>
CSS (ideas)
ā¤Big monospace font for time
ā¤Subtle gradient background
ā¤Center with Flexbox, add soft glow text-shadow
JS (flow)
ā¤Keep a state: let is24 = false;
ā¤function updateClock() {
const now = new Date()
Get hours/minutes/seconds
ā¤If 12-hour: hour = hour % 12 || 12 and add AM/PM
ā¤Format with a helper: pad(n) => n.toString().padStart(2,'0')
ā¤Build date string (e.g., Sunday, 17 September 2025)
Put into #time and #date
}
ā¤setInterval(updateClock, 1000); updateClock();
On toggle button click, flip is24 and re-render
š” Hints
Arrays help format names:
ā„const days = ["Sun","Mon","Tue","Wed","Thu","Fri","Sat"];
ā„const months = ["Jan","Feb",...,"Dec"];
ā„Use textContent to update DOM efficiently
ā„Use a single interval; donāt create multiple intervals on each click
š£ Final Notes
ā
Keep your code clean: separate HTML structure , CSS styling , and JS behavior
ā
Test edge cases (empty display on =, multiple operators, midnight formats, etc.)
Share your finished projects in the group, invite your friends , and as alwaysā
stay well, stay curious, and stay coding āļø
š Intl.NumberFormat automatically localizes numbers & symbols.
7ļøā£ Measuring Code Speed with console.time
We can measure how long a block of code takes to run.
console.time("loop test");
let sum = 0;
for (let i = 0; i < 1_000_000; i++) {
sum += i; }
console.timeEnd("loop test");
// e.g. loop test: 12ms
š Useful when comparing different ways of solving a problem.
šÆ Wrap Up
Today we learned:
ā How to move around HTML elements (DOM traversal)
ā Sorting & shuffling arrays (with destructuring explained first!)
ā Dates and how to format them
ā Currency formatting for real apps
ā Measuring performance with console.time
ā Cleaner code with destructuring
Each of these may look small, but together they give you
real-world tools youāll use in projects like calculators, dashboards, games, and even ecommerce apps.
š Week 4 Day 9 ā DOM Traverse, Sort & Shuffle, Date, Currency, Console Time, Destructuring
Hello Campers š,
First, big apology for the 3-day silence š. Sometimes life gets busy. Teaching is about consistency, and Iāll keep showing up with you. Today weāll break these topics into
tiny bites with real-world meaning .
1ļøā£ DOM Traversal (Walking around your HTML family tree)
Think of your HTML as a
family tree :
ā¤Parent = the container
ā¤Children = elements inside it
ā¤Siblings = brothers/sisters (elements at the same level)
Example HTML:
<div id="family">
<p>Child 1</p>
<p>Child 2</p>
<p>Child 3</p>
</div>
JS Traversal:
const parent = document.getElementById("family"); // Children (all kids) console.log(parent.children); // HTMLCollection
// ā¤First & Last Child
console.log(parent.firstElementChild.textContent); // "Child 1" console.log(parent.lastElementChild.textContent); // "Child 3"
// ā¤Parent of Child 2
let child2 = parent.children[1]; console.log(child2.parentElement.id); // "family"
//⤠Siblings
console.log(child2.previousElementSibling.textContent); // "Child 1"
console.log(child2.nextElementSibling.textContent); // "Child 3"
š This is how we
move around the DOM when we need not just one element but relationships.
2ļøā£ Sorting Arrays
Sorting means arranging data in
order (alphabetical, numeric, etc.).
Example: sorting numbers
let scores = [40, 100, 1, 5, 25, 10];
// Wrong (default = alphabetical!) console.log(scores.sort()); // [1, 10, 100, 25, 40, 5]
// Correct numeric sort
scores.sort((a, b) => a - b);
console.log(scores); // [1, 5, 10, 25, 40, 100]
// Descending
scores.sort((a, b) => b - a);
console.log(scores); // [100, 40, 25, 10, 5, 1]
š Always pass a
compare function when sorting numbers.
3ļøā£ Destructuring (Unpacking values quickly)
This is like saying:
āInstead of carrying a whole bag, let me just pull out the items I need.ā
Arrays:
let colors = ["red", "green", "blue"];
// Without destructuring:
let first = colors[0];
let second = colors[1];
// With destructuring:
let [c1, c2, c3] = colors;
console.log(c1); // red
console.log(c2); // green
console.log(c3); // blue
Objects:
let student = { name: "Amina", age: 20, city: "Addis" };
// Without destructuring:
let n = student.name;
let c = student.city;
// With destructuring:
let { name, city } = student;
console.log(name); // Amina
console.log(city); // Addis
š Weāll now use this in shuffling to make swaps shorter.
4ļøā£ Shuffle Arrays (Randomize order)
Imagine shuffling cards in a game. We can randomize an array using the
Fisher-Yates method .
let students = ["Aman", "Lily", "Sara", "Kebede", "Muna"];
for (let i = students.length - 1; i > 0; i--) {
let j = Math.floor(Math.random() * (i + 1));
// Swap students[i] with students[j]
[students[i], students[j]] = [students[j], students[i]]; // destructuring swap }
console.log(students);
š Thanks to destructuring, swapping values looks neat: [a, b] = [b, a];
5ļøā£ Dates (Working with real-world time)
The Date object lets us work with todayās time.
let now = new Date();
console.log(now); // full date & time
console.log(now.getFullYear()); // year
console.log(now.getMonth()); // 0-11 (0 = January)
console.log(now.getDate()); // day of month
console.log(now.getDay()); // 0-6 (0 = Sunday)
console.log(now.getHours()); // hour
console.log(now.toDateString()); // "Tue Aug 26 2025"
console.log(now.toLocaleString()); // local format
š Note: months start at
0 .
6ļøā£ Currency Formatting
When showing money, we need proper formatting.
let price = 12345.678;
// USD
console.log( new Intl.NumberFormat("en-US", { style: "currency", currency: "USD" }).format(price) ); // $12,345.68
// Ethiopian Birr
console.log( new Intl.NumberFormat("am-ET", { style: "currency", currency: "ETB" }).format(price) ); // Br 12,345.68Show more