Using <code>onDestroy</code> in Svelte to Clean Up
📖 Scenario: You are building a simple Svelte component that starts a timer when it loads. When the component is removed from the page, you want to stop the timer to avoid errors or memory leaks.
🎯 Goal: Create a Svelte component that starts a timer counting seconds and uses onDestroy to stop the timer when the component is removed.
📋 What You'll Learn
Create a variable
seconds initialized to 0Create a variable
timer to hold the interval IDUse
setInterval to increase seconds every secondUse
onDestroy to clear the interval using clearInterval(timer)💡 Why This Matters
🌍 Real World
Timers and intervals are common in web apps for clocks, countdowns, or refreshing data. Cleaning them up prevents bugs and wasted resources.
💼 Career
Understanding lifecycle hooks like <code>onDestroy</code> is essential for building reliable Svelte apps that manage resources well.
Progress0 / 4 steps