Window & Timing
In a browser, the global object is window. It represents the browser tab (or frame) your page lives in, and it's where the browser puts its APIs: document, console, timers, location, history, navigator, screen size, dialogs and more. Global functions such as setTimeout are really window.setTimeout.
Note: The examples here run inside a sandboxed frame embedded in this page, so values like the window size or URL describe that small frame, not your whole browser tab.
The window object
| Member | What it gives you |
|---|---|
window.innerWidth / innerHeight |
size of the viewport in CSS pixels |
window.scrollX / scrollY, scrollTo() |
scroll position, and scrolling |
window.location |
the current URL (href, pathname, search, hash…) |
window.history |
back/forward navigation, pushState |
window.navigator |
browser info: language, onLine, clipboard… |
window.screen |
the physical screen size |
window.devicePixelRatio |
how many device pixels per CSS pixel |
alert(), confirm(), prompt() |
simple modal dialogs |
globalThis |
the global object in any environment (window in browsers) |
<pre id="info"></pre>
<script>
const lines = [
`viewport: ${innerWidth} × ${innerHeight}`,
`pixel ratio: ${devicePixelRatio}`,
`language: ${navigator.language}`,
`online: ${navigator.onLine}`,
`location: ${location.href}`,
`globalThis === window: ${globalThis === window}`,
];
document.getElementById("info").textContent = lines.join("\n");
</script>Reacting to the window size
The resize event fires whenever the viewport changes size. For layout, CSS media queries are usually better, but window.matchMedia lets JavaScript query and watch them too:
<p id="size"></p>
<p id="mode"></p>
<script>
const size = document.getElementById("size");
const mode = document.getElementById("mode");
function showSize() {
size.textContent = `Frame is ${innerWidth}px wide`;
}
showSize();
addEventListener("resize", showSize);
const narrow = matchMedia("(max-width: 500px)");
const showMode = () => (mode.textContent = narrow.matches ? "📱 narrow layout" : "🖥️ wide layout");
showMode();
narrow.addEventListener("change", showMode);
console.log("resize the browser window to see the values update");
</script>Timing: timeouts and intervals
setTimeout runs a function once after a delay; setInterval runs it repeatedly. Both return an id that you pass to clearTimeout / clearInterval to cancel. Here's a stopwatch built from an interval:
<style> #time { font: 2em ui-monospace, monospace; } </style>
<div id="time">0.0 s</div>
<button id="start">Start</button>
<button id="stop">Stop</button>
<button id="reset">Reset</button>
<script>
let tenths = 0;
let timerId = null;
const time = document.getElementById("time");
const render = () => (time.textContent = (tenths / 10).toFixed(1) + " s");
document.getElementById("start").addEventListener("click", () => {
if (timerId !== null) return; // already running
timerId = setInterval(() => { tenths++; render(); }, 100);
});
document.getElementById("stop").addEventListener("click", () => {
clearInterval(timerId);
timerId = null;
});
document.getElementById("reset").addEventListener("click", () => {
tenths = 0;
render();
});
</script>Tip: Intervals drift: if the page is busy, ticks arrive late, and background tabs are throttled to about once per second. For accurate elapsed time, store a start time with
performance.now()and compute the difference on each tick.
Debouncing
A debounce waits until events stop arriving for a moment before acting. It's the standard trick for search boxes: don't search on every keystroke, only when the user pauses. It's built from clearTimeout + setTimeout:
<input id="search" placeholder="Type to search…" size="30">
<p id="status">Waiting for input</p>
<script>
function debounce(fn, ms) {
let id;
return (...args) => {
clearTimeout(id);
id = setTimeout(() => fn(...args), ms);
};
}
const status = document.getElementById("status");
let keystrokes = 0;
const search = debounce((text) => {
status.textContent = `Searching for "${text}" (after ${keystrokes} keystrokes)`;
console.log("search:", text);
keystrokes = 0;
}, 400);
document.getElementById("search").addEventListener("input", (e) => {
keystrokes++;
status.textContent = "typing…";
search(e.target.value);
});
</script>Smooth animation with requestAnimationFrame
For animations, don't use setInterval. requestAnimationFrame(callback) runs your callback right before the browser paints the next frame (usually 60 times a second), pauses in background tabs, and passes a high-resolution timestamp:
<style> #ball { width: 30px; height: 30px; border-radius: 50%; background: #f0db4f; position: relative; } #track { height: 40px; } </style>
<div id="track"><div id="ball"></div></div>
<button id="toggle">Pause</button>
<script>
const ball = document.getElementById("ball");
let running = true;
let last = null;
let x = 0;
let speed = 120; // pixels per second
function frame(timestamp) {
if (last !== null && running) {
const dt = (timestamp - last) / 1000; // seconds since the last frame
x += speed * dt;
const max = ball.parentElement.clientWidth - 30;
if (x > max || x < 0) { speed = -speed; x = Math.max(0, Math.min(x, max)); }
ball.style.left = x + "px";
}
last = timestamp;
requestAnimationFrame(frame);
}
requestAnimationFrame(frame);
document.getElementById("toggle").addEventListener("click", (e) => {
running = !running;
e.target.textContent = running ? "Pause" : "Resume";
});
</script>Moving by speed × elapsed time keeps the animation the same speed on 60 Hz and 120 Hz screens.
Test yourself
In a browser, what is the global object?
- document
- window
- console
- navigator
Which API is best for smooth animations?
- setInterval(fn, 16)
- setTimeout(fn, 0)
- requestAnimationFrame(fn)
- a while loop
What does a debounced search function do?
- Searches on every keystroke
- Searches only after typing pauses for a while
- Searches once per second regardless of typing
- Never searches twice for the same text