Skip to content

Use afterNextFrame for hidden origins #660

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 4 commits into from
Mar 26, 2025
Merged
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions .changeset/selfish-news-perform.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"@preact/signals": patch
---

Bail out of the animation frame with a setTimeout in case the origin page is hidden
18 changes: 15 additions & 3 deletions packages/preact/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -388,10 +388,22 @@ export function useComputed<T>(compute: () => T) {
return useMemo(() => computed<T>(() => $compute.current()), []);
}

const HAS_RAF = typeof requestAnimationFrame == "function";
function afterNextFrame(callback: () => void) {
let raf: number | undefined;

const done = () => {
clearTimeout(timeout);
if (raf != null) cancelAnimationFrame(raf);
callback();
};

const timeout = setTimeout(done, 100);
if (HAS_RAF) raf = requestAnimationFrame(done);
}

const deferEffects =
typeof requestAnimationFrame === "undefined"
? setTimeout
: requestAnimationFrame;
typeof requestAnimationFrame === "undefined" ? setTimeout : afterNextFrame;

const deferDomUpdates = (cb: any) => {
queueMicrotask(() => {
Expand Down