Browser APIs, Web Storage & Timers (The Complete Masterclass)
Welcome to Phase 13: Browser APIs and Storage! While core JavaScript provides language syntax and data structures, modern web browsers equip developers with a powerful suite of Web APIs (Browser Object Model) and Client-Side Storage Engines. In this comprehensive masterclass guide, you will master the global window environment, scheduling with setTimeout & setInterval, persistent client storage with localStorage, session-based storage with sessionStorage, HTTP Cookies, dynamic routing with the URL & History APIs, seamless clipboard copying with the Clipboard API, user coordinates with the Geolocation API, and desktop alerts with the Notifications API.
window: The global execution root object in web browsers. All global variables, BOM APIs, and viewport metrics (window.innerWidth,window.innerHeight) belong towindow.document: The DOM root node representing the HTML page content currently loaded inside the window.console: Rich developer diagnostics (console.log(),console.warn(),console.error(),console.table(), and performance timersconsole.time()/console.timeEnd()).
"use strict";
const students = [
{ name: "Ravi", role: "Frontend Dev", score: 95 },
{ name: "Sneha", role: "Backend Dev", score: 92 }
];
console.table(students); // Prints formatted interactive table in DevTools!
console.time("ArrayProcess");
const filtered = students.filter(s => s.score > 90);
console.timeEnd("ArrayProcess"); // Prints exact execution time in milliseconds
| Timer API | Execution Pattern | Cancellation Method |
|---|---|---|
setTimeout(callback, delayMs) |
Runs ONCE after delay milliseconds. | clearTimeout(timerId) |
setInterval(callback, intervalMs) |
Repeats CONTINUOUSLY every interval milliseconds. | clearInterval(intervalId) โญ Crucial to avoid memory leaks! |
"use strict";
let count = 5;
const countdownTimer = setInterval(() => {
console.log("Countdown:", count);
count--;
if (count < 0) {
clearInterval(countdownTimer); // Stop timer!
console.log("๐ Blast Off! Mission Started.");
}
}, 1000);
| Feature | localStorage โญ | sessionStorage | Cookies (document.cookie) |
|---|---|---|---|
| Persistence | Permanent (survives tab & browser close) | Tab Session Only (cleared on tab close) | Expires based on Max-Age / Expiry date |
| Storage Capacity | ~5MB - 10MB | ~5MB | ~4KB (very small) |
| Server Sent? | โ No (Pure Client-side) | โ No | โ Yes (Sent with every HTTP header) |
// 1. Store single string
localStorage.setItem("username", "Ravi");
// 2. Read single string
const username = localStorage.getItem("username");
console.log("Retrieved Username:", username); // "Ravi"
// 3. Storing Objects & Arrays with JSON
const userPreferences = { theme: "dark", fontSize: 16 };
localStorage.setItem("userPrefs", JSON.stringify(userPreferences));
// 4. Reading & Parsing JSON
const savedPrefs = JSON.parse(localStorage.getItem("userPrefs"));
console.log("Saved Theme:", savedPrefs?.theme);
// 5. Deleting item
localStorage.removeItem("username");
// localStorage.clear(); // Clears all keys for current origin
URL & URLSearchParams: Effortlessly parsing URL queries without messy string splits:const params = new URLSearchParams(window.location.search); const id = params.get("id");History API: Updating browser URL without triggering a page reload (used by React Router / Next.js):history.pushState({ page: 2 }, "Page 2", "/page-2");
"use strict";
const sampleUrl = new URL("https://www.ourcompiler.com/blog-javascript/index.html?lang=nodejs&theme=dark&page=3");
console.log("Host:", sampleUrl.hostname); // "www.ourcompiler.com"
console.log("Path:", sampleUrl.pathname); // "/blog-javascript/index.html"
// Access query params easily
const params = sampleUrl.searchParams;
console.log("Language Param:", params.get("lang")); // "nodejs"
console.log("Page Param:", params.get("page")); // "3"
console.log("Has Theme?", params.has("theme")); // true
- Clipboard API: Asynchronously write/read clipboard data:
await navigator.clipboard.writeText("Code snippet"); - Geolocation API: Access device GPS coordinates:
navigator.geolocation.getCurrentPosition(pos => console.log(pos.coords.latitude)); - Notifications API & Permissions: Request permission and dispatch native operating system desktop alerts:
Notification.requestPermission().
// 1. One-click Copy Function
async function copyToClipboard(text) {
try {
await navigator.clipboard.writeText(text);
console.log("โ
Copied to clipboard successfully!");
} catch (err) {
console.error("Failed to copy:", err);
}
}
// 2. Desktop Notification
function triggerNotification() {
if (Notification.permission === "granted") {
new Notification("Code Executed!", {
body: "Your JavaScript code executed successfully on Our Compiler.",
icon: "/logo.png"
});
} else if (Notification.permission !== "denied") {
Notification.requestPermission();
}
}
Mastering browser APIs and storage through 4 real-world production components:
Project 1: Persistent Theme Store with localStorage
const ThemeManager = {
KEY: "app_theme_preference",
saveTheme(themeName) {
localStorage.setItem(this.KEY, themeName);
document.body.className = themeName + "-theme";
},
loadTheme() {
const saved = localStorage.getItem(this.KEY) || "dark";
document.body.className = saved + "-theme";
return saved;
}
};
ThemeManager.loadTheme();
Project 2: Interactive Stopwatch with setInterval
class Stopwatch {
constructor() {
this.seconds = 0;
this.intervalId = null;
}
start() {
if (this.intervalId) return;
this.intervalId = setInterval(() => {
this.seconds++;
console.log("Elapsed Time:", this.seconds, "seconds");
}, 1000);
}
stop() {
clearInterval(this.intervalId);
this.intervalId = null;
console.log("Stopwatch Paused at:", this.seconds, "seconds");
}
reset() {
this.stop();
this.seconds = 0;
console.log("Stopwatch Reset to 0.");
}
}
const timer = new Stopwatch();
timer.start();
Project 3: One-Click Code Snippet Copier
function setupCopyButton(buttonSelector, codeSelector) {
const btn = document.querySelector(buttonSelector);
const codeBlock = document.querySelector(codeSelector);
btn?.addEventListener("click", async () => {
const text = codeBlock.textContent;
await navigator.clipboard.writeText(text);
btn.textContent = "โ
Copied!";
setTimeout(() => { btn.textContent = "๐ Copy Code"; }, 2000);
});
}
Project 4: Geolocation GPS Coordinates Finder
function findUserLocation() {
if (!navigator.geolocation) {
console.error("Geolocation is not supported by your browser!");
return;
}
navigator.geolocation.getCurrentPosition(
(position) => {
const { latitude, longitude, accuracy } = position.coords;
console.log("Latitude:", latitude);
console.log("Longitude:", longitude);
console.log("Accuracy within:", accuracy, "meters");
},
(error) => {
console.warn("Location Access Denied or Unavailable:", error.message);
},
{ enableHighAccuracy: true, timeout: 5000 }
);
}
Test localStorage item storage and retrieval in our browser live compiler:
// Store item in browser storage
localStorage.setItem("username", "Ravi");
// Retrieve item
const username = localStorage.getItem("username");
console.log("Retrieved Username:", username);