Skip to content

Commit 43c3be1

Browse files
committed
fix(virtual-core): scroll to index should only retry if still targeting the same index
1 parent 102a779 commit 43c3be1

File tree

1 file changed

+11
-0
lines changed

1 file changed

+11
-0
lines changed

packages/virtual-core/src/index.ts

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -366,6 +366,7 @@ export class Virtualizer<
366366
scrollOffset: number | null = null
367367
scrollDirection: ScrollDirection | null = null
368368
private scrollAdjustments = 0
369+
private scrollToIndexTargetIndex: number | null = null
369370
shouldAdjustScrollPositionOnItemSizeChange:
370371
| undefined
371372
| ((
@@ -970,11 +971,17 @@ export class Virtualizer<
970971

971972
index = Math.max(0, Math.min(index, this.options.count - 1))
972973

974+
// If this is called in a tight loop, we don't want our retry logic to trigger for outdated indexes.
975+
// After each async gap, we should check if we're still targeting the same index before trying to scroll.
976+
this.scrollToIndexTargetIndex = index
977+
973978
let attempts = 0
974979
const maxAttempts = 10
975980

976981
const tryScroll = (currentAlign: ScrollAlignment) => {
977982
if (!this.targetWindow) return
983+
984+
if (this.scrollToIndexTargetIndex !== index) return
978985

979986
const offsetInfo = this.getOffsetForIndex(index, currentAlign)
980987
if (!offsetInfo) {
@@ -985,6 +992,8 @@ export class Virtualizer<
985992
this._scrollToOffset(offset, { adjustments: undefined, behavior })
986993

987994
this.targetWindow.requestAnimationFrame(() => {
995+
if (this.scrollToIndexTargetIndex !== index) return
996+
988997
const currentOffset = this.getScrollOffset()
989998
const afterInfo = this.getOffsetForIndex(index, align)
990999
if (!afterInfo) {
@@ -1000,6 +1009,8 @@ export class Virtualizer<
10001009

10011010
const scheduleRetry = (align: ScrollAlignment) => {
10021011
if (!this.targetWindow) return
1012+
1013+
if (this.scrollToIndexTargetIndex !== index)
10031014

10041015
attempts++
10051016
if (attempts < maxAttempts) {

0 commit comments

Comments
 (0)