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.
<script>
import { onDestroy } from 'svelte';
let seconds = 0;
const interval = setInterval(() => seconds += 1, 1000);
onDestroy(() => clearInterval(interval));
</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
...
import { onDestroy } from 'svelte';
export function onInterval(callback, milliseconds) {
const interval = setInterval(callback, milliseconds);
onDestroy(() => {
clearInterval(interval);
});
}
...and import it into our component:
<script>
import { onInterval } from './utils.js';
let seconds = 0;
onInterval(() => seconds += 1, 1000);
</script>
App.svelte
utils.js
xxxxxxxxxx
10
1
<script>
2
import { onDestroy } from 'svelte';
3
4
let seconds = 0;
5
</script>
6
7
<p>
8
The page has been open for
9
{seconds} {seconds === 1 ? 'second' : 'seconds'}
10
</p>
Console
xxxxxxxxxx
46
1
/* App.svelte generated by Svelte v3.23.2 */
2
import {
3
SvelteComponent,
4
detach,
5
element,
6
init,
7
insert,
8
noop,
9
safe_not_equal
10
} from "svelte/internal";
11
12
import { onDestroy } from "svelte";
13
14
function create_fragment(ctx) {
15
let p;
Compiler options
result = svelte.compile(source, {
generate:
});xxxxxxxxxx
1
1
/* Add a <style> tag to see compiled CSS */