Lifecycle /
onDestroy
a. Basics b. Adding data c. Dynamic attributes d. Styling e. Nested components f. Making an app a. Assignments b. Declarations c. Statements d. Updating arrays and objects a. Declaring props b. Default values c. Spread props a. If blocks b. Else blocks c. Else-if blocks d. Each blocks e. Keyed each blocks f. Await blocks a. DOM events b. Inline handlers c. Event modifiers d. Component events e. Event forwarding f. DOM event forwarding a. Text inputs b. Numeric inputs c. Checkbox inputs d. Group inputs e. Textarea inputs f. Select bindings g. Select multiple h. Contenteditable bindings i. Each block bindings j. Media elements k. Dimensions l. This m. Component bindings n. Binding to component instances a. onMount b. onDestroy c. beforeUpdate and afterUpdate d. tick a. Writable stores b. Auto-subscriptions c. Readable stores d. Derived stores e. Custom stores f. Store bindings a. Tweened b. Spring a. The transition directive b. Adding parameters c. In and out d. Custom CSS transitions e. Custom JS transitions f. Transition events g. Local transitions h. Deferred transitions i. Key blocks a. The animate directive a. The use directive b. Adding parameters a. The class directive b. Shorthand class directive c. Inline styles d. The style directive a. Slots b. Slot fallbacks c. Named slots d. Checking for slot content e. Slot props a. setContext and getContext a. <svelte:self> b. <svelte:component> c. <svelte:element> d. <svelte:window> e. <svelte:window> bindings f. <svelte:document> g. <svelte:body> h. <svelte:head> i. <svelte:options> j. <svelte:fragment> a. Sharing code b. Exports a. The @debug tag b. HTML tags a. Congratulations!
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 counter = 0 ;
const interval = setInterval (() => counter += 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 counter = 0 ;
onInterval (() => counter += 1 , 1000 );
</ script >
Open and close the timer a few times and make sure the counter keeps ticking and the CPU load increases. This is due to a memory leak as the previous timers are not deleted. Don't forget to refresh the page before solving the example.
Show me