October 22, 2024
Chicago 12, Melborne City, USA
javascript

After changing the length of a page, why do I have to pause for a split-second before auto-scrolling?


In response to user input, I clear the nodes in a container, then copy some other nodes in. This changes the length of the page.

I wanted to scroll back to the top right after this, so added this:

window.scrollTo({ top: 0, behavior: 'smooth' });

But it wasn’t working. It never scrolled back to the top. Sometimes it scrolled partially, sometimes it didn’t do anything. It was inconsistent.

I got to wondering if it was a timing thing, so I added this, after copying the nodes in.

await new Promise(r => setTimeout(r, 10));
window.scrollTo({ top: 0, behavior: 'smooth' });

Sure enough, waiting 1/100th of a second before scrolling makes if work perfectly, every time. I’ve tried every combination of async/await, and nothing works other than pausing for a split-second before scrolling.

I’m assuming the page is calculating its height, or the required amount of scroll, in the moment before the nodes are copied in? How realistic is that assumption?

Is there some more elegant way to handle this, other than my (ugly) pause?



You need to sign in to view this answers

Leave feedback about this

  • Quality
  • Price
  • Service

PROS

+
Add Field

CONS

+
Add Field
Choose Image
Choose Video