Urgent.News

What's breaking now, across thousands of outlets.

AI

Perry Mason in: The Case of the Drifting Timer

Perry Mason in: The Case of the Drifting Timer Opening Statement You need a reactive "current time" in your Vue 3 app. A schedule grid with a red line showing "now." A live clock. A dashboard that updates every minute. Every Vue developer reaches for setInterval first. It works. But "works" and "works well" are different things. This is the story of taking a naive timer from "it ticks" to…

The case of The Drifting Timer involves Perry Mason and his quest to create a production-grade timer in a Vue 3 app. The prosecution presents four exhibits detailing various iterations and issues encountered during development.

Exhibit A introduces a memory leak caused by an uncleared interval. The timer continuously updates a ref, holding its closure in memory indefinitely when the component unmounts. This leak remains invisible and silent until it surfaces in production after users navigate the app for an extended period.

Exhibit B reveals a cleanup attempt that fails when used outside component contexts. The interval is stored in a variable and cleared on unmount, but if called from a Pinia store or any other context lacking a component instance, the cleanup does not occur. Consequently, the timer leaks silently, failing to update correctly and wasting CPU resources.

Exhibit C introduces scope-safe cleanup using Vue 3.2's onScopeDispose. This global hook operates at the current scope level, eliminating leaks when used within a component's setup or Pinia store setup. However, calling onScopeDispose without an active scope triggers a warning, preventing proper cleanup. The final composable version resolves this issue by providing a stop() function for manual disposal when no active scope exists.

The final exhibit describes the clock alignment and visibility pause solution. When the app loads at a specific time, such as 10:00:58, the clock incorrectly updates at 60-second intervals rather than aligning with the actual time. Additionally, the timer continues running when the tab is hidden, consuming unnecessary CPU power.

The final version addresses these issues by ensuring precise clock alignment and pausing the timer when the tab is inactive, resulting in a production-grade timer that functions optimally in various scenarios.

Written by urgent.news from Dev.to's reporting — not their text. Machine-written — may contain errors; check the original before relying on it.

Read the original at dev.to →

More in AI

More from Thursday 13 August →