gpt4 book ai didi

javascript - 连续运行代码而不是 do-while 循环的替代方法?

转载 作者:行者123 更新时间:2023-11-30 09:11:07 27 4
gpt4 key购买 nike

我正在使用 javascript 创建幻灯片。我创建了一个循环,负责更改我的幻灯片的 css。我希望这个循环是无限的,因为我想在每个设定的时间间隔后更换幻灯片。

但是,无限循环导致我的整个网站挂起并崩溃。我想知道是否有替代方法不会导致我的整个页面崩溃?

async function startSlideShow(slideshow, leftPos, timer) {

let slideContainer = slideshow.children[0];

//How to handle this
let index = 0;
do {
if (index === (leftPos.length - 1)) {
index = 0;
} else {
changeSlide(index);
index++;
}
} while (true);

function changeSlide(index){
setTimeout(function(){
slideContainer.style.left = "-" + leftPos[index] + "px";
console.log("-" + leftPos[index] + "px");
}, timer * index)
}
}

最佳答案

试试setInterval,默认连续调用一个函数。只需将所有计数器更新内容放入间隔函数即可。

function startSlideshow(slideshow, leftPos, timer) {
let slideContainer = slideshow.children[0];
let index = 0;
setInterval(
function () {
slideContainer.style.left = "-" + leftPos[index] + "px";
console.log("-" + leftPos[index] + "px");
index = (index + 1) % leftPos.length;
// for the range of values index can be, this is equivalent to
// index = index + 1;
// if (index == leftPos.length) index = 0;
}, timer
);
}

a % b当你划分 a 时给你余数通过 b .这给你 a什么时候a < b , 然后 0什么时候a == b . More info

关于javascript - 连续运行代码而不是 do-while 循环的替代方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58891165/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com