Xavier C.
Xavier C.

Reputation: 192

Insert a variable inside a function

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.

Upvotes: 0

Views: 62

Answers (1)

jcal
jcal

Reputation: 875

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

Upvotes: 1

Related Questions