issues with clearing setTimeout() in javascript code

58 Views Asked by At

I am trying to make a button which when clicked will stop the execution of the automatic slideshow. The clearTimeout() function isn't working for some strange reason. can someone please tell me how to make it work?

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);
}


}
1

There are 1 best solutions below

0
On

You have to clear all the timeouts present in the page.

Something like this:

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);
  }
}