Skip to content

Svelte 5: requestAnimationFrame queue grows indefinitely when document is not visible #10253

@brunnerh

Description

@brunnerh

Describe the bug

#each item animations use a RAF queue since #10119.
I suspected that this would cause the queue to grow when state updates happen while the document is not visible; such updates can e.g. be caused by web sockets or server sent events.

Reproduction

E.g. set up a server sent events endpoint in SvelteKit:

// src/routes/events/+server.js
export const GET = async () => {
    const sse = new ReadableStream({
        async start(controller) {
            for (let i = 0; i < 100; i++) {
                controller.enqueue(`data: ${i}\n\n`);
                await new Promise(resolve => setTimeout(resolve, 1000));
            }
            controller.close();
        },
    }, new CountQueuingStrategy({ highWaterMark: 1 }));

    return new Response(sse, {
        headers: {
            'Content-Type': 'text/event-stream',
            'Cache-Control': 'no-cache',
            Connection: 'keep-alive',
        },
    });
};

Update a list of items on a page based on events:

<script>
    import { onMount } from 'svelte';
    import { flip } from 'svelte/animate';

    let items = $state([]);

    onMount(() => {
        const eventSource = new EventSource('/events');
        eventSource.onmessage = event => items.unshift(event.data);

        return () => eventSource.close();
    });
</script>

<div>
    {#each items as item (item)}
        <div animate:flip>{item}</div>
    {/each}
</div>

Open page & switch to another tab.
The length of the queue (grows via schedule_raf_task) can be observed e.g. via the dev tools.

Logs

No response

System Info

System:
    OS: Windows 10 10.0.19045
    CPU: (12) x64 Intel(R) Core(TM) i7-8700K CPU @ 3.70GHz
    Memory: 13.93 GB / 31.92 GB
  Binaries:
    Node: 18.13.0 - C:\Program Files\nodejs\node.EXE
    Yarn: 1.22.19 - ~\AppData\Roaming\npm\yarn.CMD
    npm: 9.2.0 - C:\Program Files\nodejs\npm.CMD
    pnpm: 8.6.9 - ~\AppData\Local\pnpm\pnpm.EXE
  Browsers:
    Chrome: 120.0.6099.218
    Edge: Spartan (), Chromium (120.0.2210.144), ChromiumDev ()
    Internet Explorer: 11.0.19041.3636
  npmPackages:
    svelte: ^5.0.0-next.37 => 5.0.0-next.37

Severity

annoyance

Metadata

Metadata

Assignees

Labels

No labels
No labels

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions