ajay ajay - 2 months ago 7
Javascript Question

Radio buttons selection on regular interval is not working

I want to automatically change the selection on radio buttons at regular interval. I'm calling setTimeOut in for loop after every 2000ms, but radio button selection is not changing with respect to the interval I've set.
Here's my code:
HTML:

<input type="radio" id="carousel1" name="carousel" checked="checked">
<input type="radio" id="carousel2" name="carousel">
<input type="radio" id="carousel3" name="carousel">


Javascript:

function autoSlideCarousel() {
for (var n = 1; n <= 3; n++) {
setTimeout(autoSlide(n), 2000);
}
}

function autoSlide(n) {
console.log(n);
document.getElementById("carousel"+n).checked = true;
}

window.onload = autoSlideCarousel();


Here's JSFiddle link for more clarity: https://jsfiddle.net/16zmfb12/1/

Appreciate your help.

Answer

In order to avoid running all 3 setTimeouts at once, use a global var for the counter instead of a for loop, and add the setTimeout to the end of the autoSlide() function.

var n = 1;

function autoSlide(n) {
  console.log(n);
  document.getElementById("carousel"+n).checked = true;
  if (n<3) {
    setTimeout(function() {autoSlide(n+1)},2000);
  }
}        

window.onload = autoSlide(n);