Joe Vox Joe Vox - 2 months ago 17
Javascript Question

setInterval firing only once

I know this may seem a duplicate but that's not the case here.
I'm trying to create a simple Slider with an OOP approach.
So here's what I've got so far:

function Slider(){
this.totalSlides = 3;
this.sliderImagesRoot = 'images/slider/';
this.imagesLinks = [this.sliderImagesRoot + '1.png',this.sliderImagesRoot + '2.png',this.sliderImagesRoot + '3.png'];
this.titles = ['State of the Art', 'Best staff kk', 'Toratos'];
this.descriptions = ['First description, bla bla bla', 'werewr','Toraki'];
this.slideDelay = 1200;
this.currSlide = 1;

this.initSlider = function(){
var createSlide = this.createSlide();
var sliding = setInterval(function(createSlide){
createSlide();
}, 500);

}

this.createSlide = function(){
alert("er");
}
}


I think it has something to do with passing into the function, any ideas?
This is the first time I try to implement OOP in JS by the way.

Answer

You don't need create a separate constructor method for the object (initSlider in your code), the function Slider itself is the the constructor. Try something like this:

function Slider(){
    this.totalSlides = 3;
    this.sliderImagesRoot = 'images/slider/';
    this.imagesLinks = [this.sliderImagesRoot + '1.png',this.sliderImagesRoot + '2.png',this.sliderImagesRoot + '3.png'];
    this.titles = ['State of the Art', 'Best staff kk', 'Toratos'];
    this.descriptions = ['First description, bla bla bla', 'werewr','Toraki']; 
    this.slideDelay = 1200;
    this.currSlide = 1;

    var createSlide = function(){
            alert("er");  
    }
    var sliding = setInterval(function(){
        createSlide();
    }, 500);


}

and then you can construct the object like this:

var slider = new Slider();