onDestroy

To run code when your component is destroyed, use onDestroy.

For example, we can add a setInterval function when our component initialises, and clean it up when it’s no longer relevant. Doing so prevents memory leaks.

  1. <script>
  2. import { onDestroy } from 'svelte';
  3. let seconds = 0;
  4. const interval = setInterval(() => seconds += 1, 1000);
  5. onDestroy(() => clearInterval(interval));
  6. </script>

While it’s important to call lifecycle functions during the component’s initialisation, it doesn’t matter where you call them from. So if we wanted, we could abstract the interval logic into a helper function in utils.js

  1. import { onDestroy } from 'svelte';
  2. export function onInterval(callback, milliseconds) {
  3. const interval = setInterval(callback, milliseconds);
  4. onDestroy(() => {
  5. clearInterval(interval);
  6. });
  7. }

…and import it into our component:

  1. <script>
  2. import { onInterval } from './utils.js';
  3. let seconds = 0;
  4. onInterval(() => seconds += 1, 1000);
  5. </script>