Skip to content

Commit 63cdd29

Browse files
committed
feat: add onFrame lifecycle function
1 parent ad87572 commit 63cdd29

File tree

3 files changed

+39
-0
lines changed

3 files changed

+39
-0
lines changed
Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
---
2+
'svelte': minor
3+
---
4+
5+
feat: add `onFrame` lifecycle function

packages/svelte/src/index-client.js

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -161,6 +161,32 @@ export function afterUpdate(fn) {
161161
init_update_callbacks(component_context).a.push(fn);
162162
}
163163

164+
/**
165+
* The `onFrame` function schedules a callback to run on `requestAnimationFrame`. It must be called inside an effect (e.g. during component initialisation).
166+
*
167+
* `onFrame` does not run inside [server-side components](https://svelte.dev/docs/svelte/svelte-server#render).
168+
*
169+
* @template T
170+
* @param {() => NotFunction<T> | Promise<NotFunction<T>> | (() => any)} fn
171+
* @returns {void}
172+
*/
173+
export function onFrame(fn) {
174+
onMount(() => {
175+
let frame = -1;
176+
177+
function next() {
178+
frame = requestAnimationFrame(next);
179+
fn();
180+
}
181+
182+
next();
183+
184+
return () => {
185+
cancelAnimationFrame(frame);
186+
};
187+
});
188+
}
189+
164190
/**
165191
* Legacy-mode: Init callbacks object for onMount/beforeUpdate/afterUpdate
166192
* @param {ComponentContext} context

packages/svelte/types/index.d.ts

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -408,6 +408,13 @@ declare module 'svelte' {
408408
* @deprecated Use [`$effect`](https://svelte.dev/docs/svelte/$effect) instead
409409
* */
410410
export function afterUpdate(fn: () => void): void;
411+
/**
412+
* The `onFrame` function schedules a callback to run on `requestAnimationFrame`. It must be called inside an effect (e.g. during component initialisation).
413+
*
414+
* `onFrame` does not run inside [server-side components](https://svelte.dev/docs/svelte/svelte-server#render).
415+
*
416+
* */
417+
export function onFrame<T>(fn: () => NotFunction<T> | Promise<NotFunction<T>> | (() => any)): void;
411418
/**
412419
* Synchronously flushes any pending state changes and those that result from it.
413420
* */
@@ -1671,6 +1678,7 @@ declare module 'svelte/motion' {
16711678
* <input type="range" bind:value={spring.target} />
16721679
* <input type="range" bind:value={spring.current} disabled />
16731680
* ```
1681+
* @since 5.8.0
16741682
*/
16751683
export class Spring<T> {
16761684
constructor(value: T, options?: SpringOpts);

0 commit comments

Comments
 (0)