Browser APIs and StorageLesson 8.3
Basic Browser APIs: Timers, Geolocation, and Clipboard
setTimeout, setInterval, clearTimeout, clearInterval, Geolocation API, Clipboard API, Intersection Observer intro
Basic Browser APIs: Timers, Geolocation, and Clipboard
The browser exposes dozens of built-in APIs that JavaScript can use to interact with the device and environment. In this lesson we cover three important ones: timer functions for scheduling code, the Geolocation API for getting the user's location, and the Clipboard API for reading and writing text.
setTimeout and setInterval
// Run once after delay (milliseconds)
const timeoutId = setTimeout(() => {
console.log('This runs after 2 seconds');
}, 2000);
// Cancel before it runs
// clearTimeout(timeoutId);
// Run repeatedly on an interval
let count = 0;
const intervalId = setInterval(() => {
count++;
console.log(`Count: ${count}`);
if (count >= 5) {
clearInterval(intervalId);
console.log('Stopped');
}
}, 1000);Building a Countdown Timer
function startCountdown(seconds, onTick, onComplete) {
let remaining = seconds;
const intervalId = setInterval(() => {
remaining--;
onTick(remaining);
if (remaining <= 0) {
clearInterval(intervalId);
onComplete();
}
}, 1000);
return intervalId;
}
startCountdown(
10,
(s) => console.log(`${s} seconds remaining`),
() => console.log('Time is up!')
);Geolocation API
function getUserLocation() {
if (!navigator.geolocation) {
console.log('Geolocation is not supported by your browser.');
return;
}
navigator.geolocation.getCurrentPosition(
(position) => {
const { latitude, longitude } = position.coords;
console.log(`Lat: ${latitude}, Lng: ${longitude}`);
},
(error) => {
console.error('Error getting location:', error.message);
}
);
}
getUserLocation();Clipboard API
async function copyToClipboard(text) {
try {
await navigator.clipboard.writeText(text);
console.log('Copied to clipboard!');
} catch (error) {
console.error('Copy failed:', error);
}
}
async function readFromClipboard() {
try {
const text = await navigator.clipboard.readText();
console.log('Clipboard contents:', text);
} catch (error) {
console.error('Read failed:', error);
}
}
document.querySelector('#copy-btn').addEventListener('click', () => {
copyToClipboard('Hello from JavaScript!');
});