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); });.
Practice
(1/5)
1. What is the main purpose of the onDestroy function in a Svelte component?
easy
A. To run cleanup code when the component is removed from the page
B. To initialize component state when it loads
C. To update the component when data changes
D. To handle user input events
Solution
Step 1: Understand the lifecycle of a Svelte component
The onDestroy function runs when the component is about to be removed from the page.
Step 2: Identify the purpose of onDestroy
It is used to clean up things like timers or event listeners to avoid bugs or memory leaks.
Final Answer:
To run cleanup code when the component is removed from the page -> Option A
Quick Check:
onDestroy = cleanup on removal [OK]
Hint: Remember: onDestroy cleans up when component leaves [OK]
Common Mistakes:
Confusing onDestroy with onMount
Thinking onDestroy runs on data update
Using onDestroy to initialize state
2. Which of the following is the correct way to import and use onDestroy in a Svelte component?
easy
A. import { onDestroy } from 'svelte'; onDestroy.cleanup(() => { /* cleanup */ });
B. import onDestroy from 'svelte'; onDestroy(() => { /* cleanup */ });
C. import { onDestroy } from 'svelte'; onDestroy(() => { /* cleanup */ });
D. import { onDestroy } from 'svelte'; onDestroy = () => { /* cleanup */ };
Solution
Step 1: Check the import syntax
The correct import is a named import: import { onDestroy } from 'svelte';
Step 2: Check how to use onDestroy
You call onDestroy with a function to run cleanup code: onDestroy(() => { ... });
Final Answer:
import { onDestroy } from 'svelte'; onDestroy(() => { /* cleanup */ }); -> Option C
Quick Check:
Correct import and call syntax = import { onDestroy } from 'svelte'; onDestroy(() => { /* cleanup */ }); [OK]
Hint: Use named import and call onDestroy with a function [OK]
5. You want to use onDestroy to clean up multiple resources: a timer and a custom event listener. Which is the best way to do this in a Svelte component?
import { onDestroy } from 'svelte';
let timer = setInterval(() => console.log('Tick'), 1000);
function onCustomEvent() { console.log('Event'); }
window.addEventListener('custom', onCustomEvent);
// What is the correct onDestroy usage?
hard
A. onDestroy(() => { clearInterval(timer); window.removeEventListener('custom'); });
B. onDestroy(() => { clearInterval(timer); window.removeEventListener('custom', onCustomEvent); });