简体   繁体   English

如何在 javascript 中使用 SetTimeOut function 进行平滑滚动

[英]How to use SetTimeOut function for smooth scrolling in javascript

I have use setTimeOut function to smooth scrolling我已经使用setTimeOut function 来平滑滚动

But

my function didn't work properly.我的 function 无法正常工作。
It is working but not smoothly它正在工作,但并不顺利
can someone help me!有人能帮我吗!

const handleScroll = () => {
const pageCards_div = document.getElementsByClassName('page-cards')
for (let i = 0; i < 235; i++) {
  setTimeout(() => {
    pageCards_div[0].scrollLeft += 1
  }, 1000)
}

} }

Your for loop schedules 235 calls to your animation function, which will be invoked immediately one after the other, starting after 1 second.for循环安排了对 animation function 的 235 次调用,这些调用将在 1 秒后开始一个接一个地立即调用。

If you want to take one step, wait 1s, take another step, wait another 1s, etc. - you can do something like this:如果您想迈出一步,等待 1 秒,再迈出一步,再等待 1 秒,等等 - 您可以执行以下操作:

const handleScroll = () => {
const pageCards_div = document.getElementsByClassName('page-cards')

let func;
func = (remaining) => {
    if (remaining == 0) {
        return;
    }
    pageCards_div[0].scrollLeft += 1;

    setTimeout(() => {
        func(remaining - 1);
    }, 1000);
};

func(235);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM