Skip to content

chore: avoid microtasks when flushing sync #15855

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

Open
wants to merge 3 commits into
base: main
Choose a base branch
from
Open
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/polite-melons-tickle.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'svelte': patch
---

chore: avoid microtasks when flushing sync
36 changes: 23 additions & 13 deletions packages/svelte/src/internal/client/runtime.js
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,7 @@ const handled_errors = new WeakSet();
let is_throwing_error = false;

let is_flushing = false;
let is_flushing_sync = false;

/** @type {Effect | null} */
let last_scheduled_effect = null;
Expand Down Expand Up @@ -734,7 +735,9 @@ function flush_queued_effects(effects) {
export function schedule_effect(signal) {
if (!is_flushing) {
is_flushing = true;
queueMicrotask(flush_queued_root_effects);
if (!is_flushing_sync) {
queueMicrotask(flush_queued_root_effects);
}
}

var effect = (last_scheduled_effect = signal);
Expand Down Expand Up @@ -818,23 +821,30 @@ function process_effects(root) {
* @returns {T}
*/
export function flushSync(fn) {
var result;
var previously_flushing_sync = is_flushing_sync;

if (fn) {
is_flushing = true;
flush_queued_root_effects();
result = fn();
}
try {
var result;
is_flushing_sync = true;

flush_tasks();
if (fn) {
is_flushing = true;
flush_queued_root_effects();
result = fn();
}

while (queued_root_effects.length > 0) {
is_flushing = true;
flush_queued_root_effects();
flush_tasks();
}

return /** @type {T} */ (result);
while (queued_root_effects.length > 0) {
is_flushing = true;
flush_queued_root_effects();
flush_tasks();
}

return /** @type {T} */ (result);
} finally {
is_flushing_sync = previously_flushing_sync;
}
}

/**
Expand Down