0

I'm using swiper to generate 4 different sliders, each one is called using this :

var swiper2 = new Swiper

What i want is to create a function that will fire the

swiper2.slideNext(); 

every 2 seconds, so i used :

setInterval(function(){
 swiper2.slideNext();
 }, 2000);

This works great. But as i said, i have 4 different sliders, and i would like to change the number randomly every time the setInterval function is fired

I tried this

setInterval(function(){
 var randx = Math.floor(Math.random() * 4) + 1;
 swiper + randx.slideNext();
 }, 2000);

But it does not work, it returns swiper, not swiperX wher X is between 1 and 4. And throws an error because swiper does not exist, only swiper1 to swiper4.

This is obviously a lack of knowledge of JS from myself, any help appreciated.

1
  • Arrays exist for this purpose. Look into them. Commented Jan 8, 2019 at 22:58

1 Answer 1

1

you should store all swipers in an array like:

var swipers = [swiper1, swiper2, swiper3, swiper4];

and then in your interval you call:

setInterval(function(){
  var randx = Math.floor(Math.random() * 4);
  swipers[randx].slideNext();
}, 2000);
Sign up to request clarification or add additional context in comments.

2 Comments

thanks but not working : Uncaught TypeError: Cannot read property 'slideNext' of undefined
I just updated the answer, cuz i forgot to remove the +1 in the random function, since arrays start with an index of 0

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.