Browser APIs, Web Storage & Timers (The Complete Masterclass)

๐ŸŸจ JavaScript (ES2026+) ๐ŸŸข Lesson 16 ๐Ÿ“‚ Phase 13: Browser APIs & Storage ๐Ÿ“… 2026 Edition
๐Ÿ“Œ Covered in this lesson: window & document ยท Timers (setTimeout/setInterval) ยท localStorage vs sessionStorage vs Cookies ยท URL API ยท History API ยท Clipboard API ยท Geolocation ยท Notifications & Permissions ยท 4 Projects

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.

1The Global Browser Environment: window, document & console
  • window: The global execution root object in web browsers. All global variables, BOM APIs, and viewport metrics (window.innerWidth, window.innerHeight) belong to window.
  • 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 timers console.time() / console.timeEnd()).
JavaScript โ€” Console Diagnostics
"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
2Timers & Scheduling: setTimeout vs setInterval
Timer APIExecution PatternCancellation 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!
JavaScript โ€” Countdown Timer with setInterval
"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);
3Client Storage: localStorage vs sessionStorage vs Cookies
FeaturelocalStorage โญsessionStorageCookies (document.cookie)
PersistencePermanent (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)
JavaScript โ€” localStorage CRUD Operations
// 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
4URL API & History API (Single Page Application Routing)
  • 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");
JavaScript โ€” URLSearchParams Demo
"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
5Modern Web APIs: Clipboard, Geolocation & Notifications
  • 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().
JavaScript โ€” Async Clipboard & Notification APIs
// 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();
    }
}
64 Real-World Practice Projects

Mastering browser APIs and storage through 4 real-world production components:

Project 1: Persistent Theme Store with localStorage

JavaScript โ€” Theme Store
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

JavaScript โ€” Stopwatch Engine
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

JavaScript โ€” Clipboard 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

JavaScript โ€” Geolocation API
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 }
    );
}
๐Ÿ’ป Try It Yourself โ€” User Curriculum Code Example

Test localStorage item storage and retrieval in our browser live compiler:

JavaScript Storage โ–ถ Run Code
// Store item in browser storage
localStorage.setItem("username", "Ravi");

// Retrieve item
const username = localStorage.getItem("username");
console.log("Retrieved Username:", username);
Run Code in Our Compiler โ†’
OC
Written and reviewed by Our Compiler Technical Team ยท Updated for JavaScript ES2026+