Building a Floating Mini-Timer with Document PiP
When developers, speakers, or students use web timers while working in IDEs, reading research papers, or presenting keynote slides, switching tabs to monitor or control the timer disrupts deep work and creates friction. Every time you have to alt tab back to a browser tab just to check how many minutes remain in a focus sprint, your cognitive flow is interrupted. Traditional web applications are…
Developers and students often rely on web timers while working in IDEs or presenting slides. However, opening a separate browser tab to check remaining time disrupts deep work and introduces friction. Traditional web apps are confined to tab borders, requiring wrapper frameworks or legacy controls for persistent windows. This story explores building a floating mini-timer using the Document Picture-in-Picture API.
The Document Picture-in-Picture API enables web apps to open always-on-top windows with full HTML content, bypassing the tab frame. Unlike video pip, which requires rendering a canvas into a video stream, this API provides an interactive Document context. The child window runs on the same JavaScript thread as the parent, allowing direct referencing and invocation of objects without serialization overhead.
To initialize the mini-timer, an asynchronous function is used to request a new PiP window with specified dimensions. The window is then configured with scoped CSS, container elements, and UI controls. The PiP window operates on the same JavaScript thread as the parent, enabling direct manipulation of its DOM and shared state.
Lifecycle management is crucial for proper cleanup when the floating window is closed. Listening for the pagehide event ensures the internal state is cleaned up, preventing memory leaks. The zero-drift clock synchronization technique uses a single monotonic end time derived from performance.now() to calculate remaining time. This ensures both the parent tab and PiP window display identical time values, even when background tab throttling occurs.
To enhance usability, ergonomic keyboard handling is implemented directly on the PiP window's document instance. Spacebar toggles timer states, and the escape key closes the window. This direct event handling maintains focus within the floating mini-timer, minimizing interruptions to the user's workflow.
Written by urgent.news from Dev.to's reporting — not their text. Machine-written — may contain errors; check the original before relying on it.
