0
0
Svelteframework~5 mins

onDestroy in Svelte

Choose your learning style9 modes available
Introduction

The onDestroy function lets you run code when a Svelte component is removed from the page. This helps clean up things like timers or event listeners so your app stays fast and tidy.

You start a timer or interval in a component and want to stop it when the component is gone.
You add event listeners to the window or document and want to remove them when the component is removed.
You open a WebSocket or other connection and want to close it when the component is destroyed.
You want to clear any resources or cancel subscriptions when the component is no longer visible.
Syntax
Svelte
import { onDestroy } from 'svelte';

onDestroy(() => {
  // cleanup code here
});

You import onDestroy from 'svelte' to use it.

The function you pass to onDestroy runs once when the component is removed.

Examples
This logs a message when the component is destroyed.
Svelte
import { onDestroy } from 'svelte';

onDestroy(() => {
  console.log('Component is gone');
});
This example starts a timer and stops it when the component is removed.
Svelte
import { onDestroy } from 'svelte';

const interval = setInterval(() => {
  console.log('Tick');
}, 1000);

onDestroy(() => {
  clearInterval(interval);
});
Sample Program

This component increases a number every second. When the component is removed, the timer stops and a message logs in the console.

Svelte
<script>
  import { onDestroy } from 'svelte';

  let count = 0;

  const interval = setInterval(() => {
    count += 1;
  }, 1000);

  onDestroy(() => {
    clearInterval(interval);
    console.log('Interval cleared');
  });
</script>

<p>Count: {count}</p>
OutputSuccess
Important Notes

Always clean up timers, listeners, or subscriptions in onDestroy to avoid memory leaks.

onDestroy runs only once per component instance.

Summary

onDestroy runs code when a Svelte component is removed.

Use it to clean up timers, event listeners, or other resources.

Helps keep your app fast and bug-free by avoiding leftover tasks.