Categories
JavaScript Answers

How to add smooth auto scroll by with JavaScript?

Spread the love

Sometimes, we want to add smooth auto scroll by with JavaScript.

In this article, we’ll look at how to add smooth auto scroll by with JavaScript.

How to add smooth auto scroll by with JavaScript?

To add smooth auto scroll by with JavaScript, we can call setTimeout recursively to scroll the page.

For instance, we write:

const pageScroll = () => {
  window.scrollBy(0, 1);
  setTimeout(pageScroll, 10);
}
pageScroll()

to define the pageScroll function to scroll the page.

In it, we call window.scrollBy to scroll 1 pixel down.

Then we call setTimeout with pageScroll and 10 to call pageScroll again 10 milliseconds later.

Conclusion

To add smooth auto scroll by with JavaScript, we can call setTimeout recursively to scroll the page.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *