Search code examples
javascriptloopsonload

Onload timer reset or restart


Is there any way I can reset the time of this onload?

function auto(){
  setInterval(slide, 5000);
}
window.onload = auto;

In my case, when I change slides manually through the checkboxes, the timer does not reset and basically passes the chosen slide quickly, because the counter did not reset along with the slide() function.

I use this for listerning the slides indexs (Checkboxes), and reload slideshow script.

function check(input) {
    //set checked of clicked object
  slideContador = input.name;
  slide();
}

function slide() {
  if(slideContador >= slideTamanho) {
    slideContador = 0;
  }
  document.getElementById('slide-link').href = slideLink[slideContador];  
  document.getElementById('slide-img').src = slideImg[slideContador];
  document.getElementById('slideshow-bg').style.backgroundImage = "url('" + slideFundo[slideContador] + "')";
//Desmarca checkboxes
var checkboxes = document.getElementsByClassName("rounded-checkbox");
        for(var i = 0; i < checkboxes.length; i++){
            //uncheck all
            if(checkboxes[i].checked == true)
            {
                checkboxes[i].checked = false;
            }
        }
var element = document.getElementsByName(slideContador)[0];
element.checked = true;
//Almenta o contador
slideContador++;
}

Solution

  • Use clearInterval to remove the timer.

    let timer = null
    function auto(shouldSlide){
      if (timer) window.clearInterval(timer);
      timer = window.setInterval(slide, 5000);
      if (shouldSlide) slide();
    }
    window.addEventListener('load', function() { auto(); });
    
    function check(input) {
      slideContador = input.name;
      auto(true);
    }