From cd8d4dc12b874b32695ac0c52e186d8ae6f35054 Mon Sep 17 00:00:00 2001 From: Weston Ruter Date: Tue, 15 Oct 2024 18:56:51 -0700 Subject: [PATCH] Leverage scheduler.yield in splitTask when available (#66001) * Leverage scheduler.yield in splitTask when available * Eliminate extra Promise when using scheduler.yield() Co-authored-by: swissspidy * Avoid needlessly re-checking whether scheduler.yield() is defined * Remove needless function wrapper * Ensure that scheduler is context object to yield function * Remove needless async * Reduce verbosity of scheduler.yield() existence check * Fix return type for scheduler.yield() Co-authored-by: Brendan Kenny * Define scheduler and scheduler.yield as optional Co-authored-by: Brendan Kenny --------- Unlinked contributors: brendankenny, LeszekSwirski. Co-authored-by: felixarntz --- packages/interactivity/src/utils.ts | 22 ++++++++++++++++------ 1 file changed, 16 insertions(+), 6 deletions(-) diff --git a/packages/interactivity/src/utils.ts b/packages/interactivity/src/utils.ts index 4f10ed517de50..9cd6f8bebb0d1 100644 --- a/packages/interactivity/src/utils.ts +++ b/packages/interactivity/src/utils.ts @@ -22,6 +22,14 @@ interface Flusher { readonly dispose: () => void; } +declare global { + interface Window { + scheduler?: { + readonly yield?: () => Promise< void >; + }; + } +} + /** * Executes a callback function after the next frame is rendered. * @@ -48,12 +56,14 @@ const afterNextFrame = ( callback: () => void ) => { * * @return Promise */ -export const splitTask = () => { - return new Promise( ( resolve ) => { - // TODO: Use scheduler.yield() when available. - setTimeout( resolve, 0 ); - } ); -}; +export const splitTask = + typeof window.scheduler?.yield === 'function' + ? window.scheduler.yield.bind( window.scheduler ) + : () => { + return new Promise( ( resolve ) => { + setTimeout( resolve, 0 ); + } ); + }; /** * Creates a Flusher object that can be used to flush computed values and notify listeners.