Documentation Index
Fetch the complete documentation index at: https://mintlify.com/sveltejs/svelte/llms.txt
Use this file to discover all available pages before exploring further.
The getAbortSignal() function returns an AbortSignal that automatically aborts when the current $derived or $effect re-runs or is destroyed. This is useful for cancelling ongoing async operations.
Import
import { getAbortSignal } from 'svelte';
Signature
function getAbortSignal(): AbortSignal;
Returns
A standard AbortSignal that aborts when the effect re-runs or is destroyed
Usage
Cancelling fetch requests
<script>
import { getAbortSignal } from 'svelte';
let { id } = $props();
async function getData(id) {
const response = await fetch(`/api/items/${id}`, {
signal: getAbortSignal()
});
return await response.json();
}
// This will automatically cancel the previous fetch when id changes
const data = $derived(await getData(id));
</script>
<div>{JSON.stringify(data)}</div>
Cleanup in effects
<script>
import { getAbortSignal } from 'svelte';
let active = $state(true);
$effect(() => {
if (active) {
const signal = getAbortSignal();
// Start a long-running operation
longRunningTask({ signal })
.then(() => console.log('completed'))
.catch(err => {
if (err.name === 'AbortError') {
console.log('cancelled');
}
});
}
});
</script>
<button onclick={() => active = !active}>
Toggle
</button>
With intervals
<script>
import { getAbortSignal } from 'svelte';
let count = $state(0);
$effect(() => {
const signal = getAbortSignal();
const interval = setInterval(() => {
if (!signal.aborted) {
count++;
}
}, 1000);
signal.addEventListener('abort', () => {
clearInterval(interval);
});
});
</script>
<p>Count: {count}</p>
Error handling
<script>
import { getAbortSignal } from 'svelte';
let { query } = $props();
async function search(query) {
try {
const response = await fetch(`/search?q=${query}`, {
signal: getAbortSignal()
});
return await response.json();
} catch (err) {
// Ignore abort errors - they're expected when query changes
if (err.name !== 'AbortError') {
console.error('Search failed:', err);
}
return null;
}
}
const results = $derived(await search(query));
</script>
Notes
- Must be called inside a
$derived or $effect
- Each call returns a unique signal
- The signal aborts automatically on cleanup
- Works with any API that accepts an AbortSignal
- Helps prevent race conditions and memory leaks
See also