Skip to content

Instantly share code, notes, and snippets.

@gingerrific
Created May 29, 2014 00:20
Show Gist options
  • Save gingerrific/73ddf44e53c953a7724f to your computer and use it in GitHub Desktop.
Save gingerrific/73ddf44e53c953a7724f to your computer and use it in GitHub Desktop.
this.imageSlide = function () {
return $('.image-slider').css({'margin-left': '-=392px'});
}
// interval function that will call the imageSlide animation every set interval (parameter or default of 2400)
// if the counter hits the array length - 1, it will reset itself back to 0 and also move the image slider to 0.
this.changeImage = function () {
setInterval(function () {
this.imageSlide();
i += 1;
// when the counter hits the end of the array (in this case) return to one. need to set to index.length instead of '6'
// also resets the image slider to the first image
if (i == array.length - 1) {
i=1;
$('.image-slider').css({'margin-left': '0px', 'transition': 'none'});
}
}, intervalTime);
};
@gingerrific
Copy link
Author

I couldn't figure out why the above wouldn't work and I kept getting "undefined is not a function" with a reference to line 9. Any other code issues aside, as this was inside a constructor, I was baffled why this wouldn't work. I could run 'var slideshow = new Slider()' and 'slideshow.imageSlide()' was totally valid. Then Mason reminded me of the wonders of scope and 'this' usage.

From MDN:
Code executed by setInterval() is run in a separate execution context to the function from which it was called. As a consequence, the this keyword for the called function will be set to the window (or global) object, it will not be the same as the this value for the function that called setTimeout/setInterval.

In my scenario, 'this' was called from within and thus, window.imageSlide() is indeed, undefined.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment