From Leaky setInterval to Production-Grade Vue 3 Timer: A Four-Step Refactor
A Vue 3 developer walkthrough examines how a simple reactive current-time implementation using setInterval can silently leak memory when a component unmounts without clearing the interval. The article traces four iterations of improvement, highlighting how storing the interval reference and calling clearInterval in onUnmounted fixes the basic leak but fails outside a component context. Vue's onScopeDispose is presented as a more robust alternative, automatically registering cleanup within any active effect scope, including Pinia setup stores. Additional issues covered include timer drift — where a 60-second interval fires relative to page load rather than clock boundaries — and unnecessary CPU usage when the browser tab is hidden. The final recommended pattern wraps all four concerns into a composable that aligns ticks to the top of the minute, pauses when the tab is not visible, and cleans up safely in any Vue scope.
This is an AI-generated summary. ShortSingh links to the original source for the complete article.
Discussion (0)
Log in to join the discussion and vote.
Log in