I'm having an issue with building a Javascript object, and calling methods within that object using setTimeout. I've tried various workarounds, but always during the second part of my loop the scope becomes the window object rather than my custom object. Warning: I'm pretty new at javascript.
my code:
$(function() {
slide1 = Object.create(slideItem);
slide1.setDivs($('#SpotSlideArea'));
slide1.loc = 'getSpot';
slide2 = Object.create(slideItem);
slide2.setDivs($('#ProgSlideArea'));
slide2.loc = 'getProg';
slide2.slide = 1;
setTimeout('triggerSlide(slide1)', slide1.wait);
setTimeout('triggerSlide(slide2)', slide2.wait);
});
function triggerSlide(slideObject) {
slideObject.changeSlide(slideObject);
}
var slideItem = {
div1: null,
div2: null,
slide: 0,
wait: 15000,
time: 1500,
loc: null,
changeSlide: function(self) {
this.slide ? curDiv = this.div1:curDiv = this.div2;
$(curDiv).load(location.pathname + "/" + this.loc, this.slideGo(self));
},
setDivs: function(div) {
var subDivs = $(div).children();
this.div1 = subDivs[0];
this.div2 = subDivs[1];
},
slideGo: function(self) {
if(this.slide) {
$(this.div2).animate({
marginLeft: "-300px"
}, this.time);
$(this.div1).animate({
marginLeft: "0"
}, this.time);
setTimeout('triggerSlide(self)', this.wait);
} else {
$(this.div1).animate({
marginLeft: "300px"
}, this.time);
$(this.div2).animate({
marginLeft: "0"
}, this.time);
setTimeout('triggerSlide(self)', this.wait);
}
this.slide ? this.slide=0:this.slide=1;
}
}
My latest attempt was building the helper function triggerSlide so that I could attempt to pass the reference to the object through my methods, but even that doesn't seem to work.
I could use setInterval and it works, however:
- I want to ensure the animation has completed before the timer restarts
- I don't learn how to get around the issue that way. :)