Parameters
Optional callback function to execute before flushing. Any state changes made in this function will be flushed synchronously before
flushSync returnsReturns
If a callback is provided, returns the result of calling the callback. Otherwise returns
voidExamples
Basic synchronous updates
Measuring DOM after update
Focusing elements after render
Synchronizing with external libraries
Sequential updates
Without callback
Use cases
- DOM measurements: When you need to measure element dimensions immediately after a state change
- Focus management: Setting focus on elements that are conditionally rendered
- Third-party integrations: Synchronizing Svelte state updates with external libraries that expect synchronous DOM updates
- Testing: Ensuring state updates complete before assertions run
- Animations: Starting animations that depend on the final rendered state
Performance considerations
flushSync()is synchronous and can block the main thread if there are many updates- Use sparingly, as it bypasses Svelte’s optimized batching of updates
- In most cases,
tick()is preferred for waiting on asynchronous updates - Multiple rapid calls to
flushSync()can hurt performance
Notes
- Unlike
tick(), which returns a Promise,flushSync()is completely synchronous - All effects and DOM updates are guaranteed to complete before
flushSync()returns - If called without a callback, it flushes any pending updates that were scheduled before the call
- This is useful when you need immediate DOM updates, but should be used judiciously