javascript setInterval函数不为我工作

我尝试创建一个slideShow,我需要通过新参数重试我的函数,但是当我尝试使用setInterval()函数时,它只运行一次。为什么是真的?javascript setInterval函数不为我工作

var sIndex = 0; 

var slide = document.getElementsByClassName('slide');

function slider(n) {

if (sIndex + n >= 0 && sIndex + n <= slide.length - 1) {

slide[sIndex].style.display = "none";

sIndex += n;

slide[sIndex].style.display = "block";

} else if (sIndex + n < 0) {

slide[sIndex].style.display = "none";

sIndex = slide.length - 1;

slide[sIndex].style.display = "block";

} else if (sIndex + n > slide.length - 1) {

slide[sIndex].style.display = "none";

sIndex = 0;

slide[sIndex].style.display = "block";

}

}

setInterval(function() {

slider(sIndex);

}, 2000);

回答:

sIndex stay 0所有的时间都在看你的代码。

var sIndex = 0;  

var slide = document.getElementsByClassName('slide');

function slider(n) {

// first run: n=0 plus sIndex=0, leads to sIndex stays 0 every loop

if (sIndex + n >= 0 && sIndex + n <= slide.length - 1) {

slide[sIndex].style.display = "none";

sIndex += n;

slide[sIndex].style.display = "block";

} else if (sIndex + n < 0) {

slide[sIndex].style.display = "none";

sIndex = slide.length - 1;

slide[sIndex].style.display = "block";

} else if (sIndex + n > slide.length - 1) {

slide[sIndex].style.display = "none";

sIndex = 0;

slide[sIndex].style.display = "block";

}

console.log(new Date(), sIndex)

}

setInterval(function() {

slider(sIndex);

}, 2000);

<div class="slide"></div>

编辑:我的答案给出的理由,但没有解决方案。 @Satpal的代码给出了一个:删除n并添加1。

回答:

你不需要变量n删除

var sIndex = 0; 

var slide = document.getElementsByClassName('slide');

function slider() {

if (sIndex >= 0 && sIndex<= slide.length - 1) {

slide[sIndex].style.display = "none";

sIndex += 1;

slide[sIndex].style.display = "block";

} else if (sIndex < 0) {

slide[sIndex].style.display = "none";

sIndex = slide.length - 1;

slide[sIndex].style.display = "block";

} else if (sIndex > slide.length - 1) {

slide[sIndex].style.display = "none";

sIndex = 0;

slide[sIndex].style.display = "block";

}

}

setInterval(slider, 2000);

以上是 javascript setInterval函数不为我工作 的全部内容, 来源链接: utcz.com/qa/262015.html

回到顶部