Skip to content

Commit

Permalink
fix(gatsby-react-router-scroll): debounce function for scollListener (#…
Browse files Browse the repository at this point in the history
…26933)

Co-authored-by: Ward Peeters <ward@coding-tech.com>
  • Loading branch information
ahmetcanaydemir and wardpeet committed Mar 1, 2021
1 parent 002aae6 commit 2f40b0a
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 2 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,7 @@ describe(`Scroll behaviour`, () => {
expect(win.scrollY).not.to.eq(0, 0)

cy.scrollTo(`bottom`)
cy.wait(500) // allow ScrollContext to update scroll position store
cy.go(`back`).waitForRouteChange()
cy.go(`forward`).waitForRouteChange()

Expand Down
21 changes: 19 additions & 2 deletions packages/gatsby-react-router-scroll/src/scroll-handler.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -25,12 +25,29 @@ export class ScrollHandler extends React.Component<

_stateStorage: SessionStorage = new SessionStorage()

// @see https://www.html5rocks.com/en/tutorials/speed/animations/
_isTicking = false
_latestKnownScrollY = 0
scrollListener = (): void => {
const { key } = this.props.location
this._latestKnownScrollY = window.scrollY

if (!this._isTicking) {
this._isTicking = true
requestAnimationFrame(this._saveScroll.bind(this))
}
}

_saveScroll(): void {
const key = this.props.location.key || null

if (key) {
this._stateStorage.save(this.props.location, key, window.scrollY)
this._stateStorage.save(
this.props.location,
key,
this._latestKnownScrollY
)
}
this._isTicking = false
}

componentDidMount(): void {
Expand Down

0 comments on commit 2f40b0a

Please sign in to comment.