Skip to content

Conversation

@joshestein
Copy link
Contributor

@joshestein joshestein commented Jan 28, 2025

If a callback within batchedCallbacks calls assign we have an infinite loop. Removing the callback from batchedCallbacks before executing it breaks this loop.

Consider a callback calling assign. assign will call batch, which will loop through all batchedCallbacks and execute each one. If one of those callbacks calls assign we will continue indefinitely.

By first removing the callback from batchedCallbacks, then executing we ensure that when the callback calls assign the callback is no longer part of the enqueued batchedCallbacks.

Minimal example with infinite loop:

import { observe } from "@mathigon/boost";

const state = observe<{ count: number }>({ count: 0 });
const model = observe<{ field: string }>({ field: "value" });

model.watch(({ field }) => {
  state.assign({ count: field.length });
});

model.assign({ field: "new value" });

If a `callback` within `batchedCallbacks` calls `assign` we have an
infinite loop. Removing the callback from `batchedCallbacks` before
executing it breaks this loop.

Consider a callback calling `assign`. `assign` will call `batch`, which
will loop through all `batchedCallbacks` and execute each one. If one of
those callbacks calls `assign` we will continue indefinitely.

By first removing the callback from `batchedCallbacks`, then executing
we ensure that when the callback calls `assign` the callback is no
longer part of the enqueued `batchedCallbacks`.
@joshestein joshestein changed the title Delete before executing batched callback Delete batched callback before executing Jan 28, 2025
@joshestein joshestein requested a review from kairacat January 28, 2025 21:08
@plegner plegner merged commit f613c1b into master Jan 29, 2025
6 checks passed
@plegner plegner deleted the josh/batched-callback-assign-loop branch January 29, 2025 15:07
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Development

Successfully merging this pull request may close these issues.

3 participants