0

我正在尝试制作一个按钮,单击该按钮将停止执行自动幻灯片。clearTimeout() 函数由于某些奇怪的原因无法正常工作。有人可以告诉我如何使它工作吗?

var button = document.getElementById("button");
button.addEventListener("click",stop);
function stop(){
  **clearTimeout(t);**
}

window.addEventListener("load",finalResult);

**var t = setTimeout(function(){finalResult()},0);**

function finalResult(){
  getFirstImage();

  function getFirstImage(){
   img1.style.display = "block";
    setTimeout(getSecondImage,3000);
}

 function getSecondImage(){
    img1.style.display = "none";
    img2.style.display = "block";
    setTimeout(getThirdImage,3000);
  }

 function getThirdImage(){
  img3.style.display = "block";
  img2.style.display = "none";
  setTimeout(getFourthImage,3000);
}

 function getFourthImage(){
  img4.style.display = "block";
  img3.style.display = "none";
  setTimeout(loopAgain,3000);
}

function loopAgain(){
  img4.style.display = "none";
  setTimeout(getFirstImage,0);
}


}
4

1 回答 1

1

您必须清除页面中存在的所有超时。

像这样的东西:

var button = document.getElementById("button");
button.addEventListener("click", stop);

function stop() {
  clearTimeout(t);
  clearTimeout(a);
  clearTimeout(b);
  clearTimeout(c);
  clearTimeout(d);
  clearTimeout(e);
}

window.addEventListener("load", finalResult);

var t = setTimeout(function() {
  finalResult()
}, 100);

var a, b, c, d, e;

function finalResult() {
  getFirstImage();

  function getFirstImage() {
    img1.style.display = "block";
     a = setTimeout(getSecondImage, 3000);
  }

  function getSecondImage() {
    img1.style.display = "none";
    img2.style.display = "block";
    b = setTimeout(getThirdImage, 3000);
  }

  function getThirdImage() {
    img3.style.display = "block";
    img2.style.display = "none";
    c = setTimeout(getFourthImage, 3000);
  }

  function getFourthImage() {
    img4.style.display = "block";
    img3.style.display = "none";
    d = setTimeout(loopAgain, 3000);
  }

  function loopAgain() {
    img4.style.display = "none";
    e = setTimeout(getFirstImage, 0);
  }
}
于 2017-01-10T09:41:29.483 回答