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.