0
0
Svelteframework~15 mins

onDestroy in Svelte - Mini Project: Build & Apply

Choose your learning style9 modes available
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 0
Create a variable timer to hold the interval ID
Use setInterval to increase seconds every second
Use 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
1
Set up the seconds variable
Create a variable called seconds and set it to 0 inside the <script> tag.
Svelte
Hint

Use let seconds = 0; inside the <script> tag.

2
Create the timer variable
Add a variable called timer inside the <script> tag to hold the interval ID. Initialize it without a value.
Svelte
Hint

Declare let timer; without assigning a value yet.

3
Start the timer with setInterval
Inside the <script> tag, assign timer to a setInterval that increases seconds by 1 every 1000 milliseconds.
Svelte
Hint

Use timer = setInterval(() => { seconds += 1; }, 1000); to update seconds every second.

4
Use onDestroy to clear the timer
Import onDestroy from 'svelte' and use it inside the <script> tag to clear the interval by calling clearInterval(timer) when the component is destroyed.
Svelte
Hint

Use import { onDestroy } from 'svelte'; and then onDestroy(() => { clearInterval(timer); });.