javascript setInterval函数对我不起作用

时间:2016-12-30 07:59:28

标签: javascript

我尝试创建一个slideShow,我需要通过新参数重试我的函数,但是当我尝试使用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);

2 个答案:

答案 0 :(得分: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);

答案 1 :(得分:1)

sIndex一直保持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代替。