onDestroy runs in a Svelte component?Consider a Svelte component that uses onDestroy to clean up resources. What is the expected behavior when the component is removed from the page?
import { onDestroy } from 'svelte'; let timer; onDestroy(() => { clearInterval(timer); console.log('Cleanup done'); }); timer = setInterval(() => console.log('Tick'), 1000);
Think about when onDestroy callbacks run in the component lifecycle.
onDestroy runs when the component is removed from the DOM. It is used to clean up things like timers or subscriptions. So the interval stops and the cleanup message logs at that time.
Given this Svelte component code, what will be logged to the console after the component is removed?
import { onDestroy } from 'svelte'; let count = 0; const interval = setInterval(() => { count += 1; console.log(count); }, 500); onDestroy(() => { clearInterval(interval); console.log('Stopped at', count); });
Consider how intervals and onDestroy interact over time.
The interval logs increasing numbers every 500ms. When the component unmounts, onDestroy clears the interval and logs the last count value.
onDestroy in Svelte?Choose the code snippet that correctly registers an onDestroy callback in a Svelte component.
Remember how onDestroy is used as a function to register callbacks.
Option C correctly imports onDestroy and calls it with a callback function. Other options misuse assignment, redeclaration, or nonexistent methods.
onDestroy callback not run?Look at this Svelte component code. Why does the onDestroy callback never execute?
import { onDestroy } from 'svelte'; function cleanup() { console.log('Cleaning up'); } // Missing onDestroy call cleanup();
Check how onDestroy is supposed to be used to register callbacks.
The code calls cleanup() immediately but never registers it with onDestroy. So no cleanup happens on component removal.
onDestroy behave with nested components in Svelte?Consider a parent Svelte component that includes a child component. Both use onDestroy callbacks. When the parent is removed from the DOM, which onDestroy callbacks run and in what order?
<!-- Parent.svelte --> <script> import Child from './Child.svelte'; import { onDestroy } from 'svelte'; onDestroy(() => console.log('Parent destroyed')); </script> <Child /> <!-- Child.svelte --> <script> import { onDestroy } from 'svelte'; onDestroy(() => console.log('Child destroyed')); </script>
Think about how nested components unmount in Svelte.
When the parent unmounts, Svelte first destroys child components, running their onDestroy callbacks, then runs the parent's onDestroy. This ensures proper cleanup from child to parent.