Skip to content
Draft
Show file tree
Hide file tree
Changes from all 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/tasty-kangaroos-greet.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'svelte': minor
---

feat: add `onAnimationFrame` lifecycle function
26 changes: 26 additions & 0 deletions packages/svelte/src/index-client.js
Original file line number Diff line number Diff line change
Expand Up @@ -198,6 +198,32 @@ export function afterUpdate(fn) {
init_update_callbacks(component_context).a.push(fn);
}

/**
* The `onAnimationFrame` function schedules a callback to run on `requestAnimationFrame`. It must be called inside an effect (e.g. during component initialisation).
*
* `onAnimationFrame` does not run inside [server-side components](https://svelte.dev/docs/svelte/svelte-server#render).
*
* @template T
* @param {() => NotFunction<T> | Promise<NotFunction<T>> | (() => any)} fn
* @returns {void}
*/
export function onAnimationFrame(fn) {
if (component_context === null) {
lifecycle_outside_component('onAnimationFrame');
}

user_effect(() => {
let frame = requestAnimationFrame(function next() {
frame = requestAnimationFrame(next);
fn();
});

return () => {
cancelAnimationFrame(frame);
};
});
}

/**
* Legacy-mode: Init callbacks object for onMount/beforeUpdate/afterUpdate
* @param {ComponentContext} context
Expand Down
1 change: 1 addition & 0 deletions packages/svelte/src/index-server.js
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ export function onDestroy(fn) {
export {
noop as beforeUpdate,
noop as afterUpdate,
noop as onAnimationFrame,
noop as onMount,
noop as flushSync,
run as untrack
Expand Down
7 changes: 7 additions & 0 deletions packages/svelte/types/index.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -410,6 +410,13 @@ declare module 'svelte' {
* @deprecated Use [`$effect`](https://svelte.dev/docs/svelte/$effect) instead
* */
export function afterUpdate(fn: () => void): void;
/**
* The `onAnimationFrame` function schedules a callback to run on `requestAnimationFrame`. It must be called inside an effect (e.g. during component initialisation).
*
* `onAnimationFrame` does not run inside [server-side components](https://svelte.dev/docs/svelte/svelte-server#render).
*
* */
export function onAnimationFrame<T>(fn: () => NotFunction<T> | Promise<NotFunction<T>> | (() => any)): void;
/**
* Create a snippet programmatically
* */
Expand Down