stefan-0905 stefan-0905 - 3 months ago 14
Javascript Question

Calling setInterval from within function

I'm making a slider and i ran into problem. I'm practicing modular

js
and this code works fine for the first time, but
setInterval
won't repeat itself so the slides continue changing. How to make it work? Thanks in advance.

var currentSlide = 1;
var slider = {

init: function(){
this.cacheDom();
this.setInt();
},
cacheDom: function(){
this.$panel = $('.slider');
this.$actPan = this.$panel.find('.panel.active');
},
setInt: function(){
return setInterval(this.mainFunction(), 3000);
},
mainFunction: function(){
this.$actPan.fadeOut(2000, this.showNextPanel());
this.$panel.find('.tabs li:nth-child('+ currentSlide +')').find('img').attr('src', 'images/g4228.png');
},
showNextPanel: function(){
this.$panel.find('#panel' + currentSlide).removeClass('active');
this.revert();
},
revert: function(){
currentSlide++;
if(currentSlide === 4){currentSlide = 1;}
this.$panel.find('.tabs li:nth-child('+ currentSlide +')').find('img').attr('src', 'images/g4228.png');
this.$panel.find('#panel' + currentSlide).fadeIn(2000, this.adder());
},
adder: function(){
this.$panel.find('#panel' + currentSlide).addClass('active');
}
};

slider.init();


So, I'm thinking that only
setInt
and
init
functions needs changing.

Answer

The problem is this line:

return setInterval(this.mainFunction(), 3000);

This is calling this.mainFunction() and passing the result to setInterval; setInterval needs to be passed a function to call on an interval. Replace that with this:

return setInterval(this.mainFunction.bind(this), 3000);

The bind is needed so that this is preserved when setInterval calls it.