0

So I'd like to store setInterval as an object property because I often like to use the phrase "autoPlay" to describe a rotator that starts immediately. When I use "autoPlay" more than once in a series of scripts, my JS gets tripped up when I try to clear them, because it's not sure which one to clear. My remedy is to put it somewhere as a property, so I can access it through an object, like "newsRotator.autoPlay". The problem is, I'm not sure how to store it that way, since it usually gets placed in a basic variable like so:

autoPlay = setInterval(this.forwardSlide, 5000);

This is an example one of my attempts at storing it as an object property, which fails to clear the interval:

var newsRotator = {
    run: function () {
        $('.arrow').on('click', function (e) {
            e.preventDefault();
            clearInterval(newsRotator.autoPlay);
            if ($(this).hasClass('back')) {
                newsRotator.backSlide();
            } else {
                newsRotator.forwardSlide();
            }
        });
    },
    backSlide: function () {
        (goes back one slide)
    },
    forwardSlide: function () {
        (goes forwardone slide)
    },
    autoPlay: setInterval(this.forwardSlide, 5000),
    init: function () {
        this.run();
    }
}

newsRotator.init()
thiirteen
  • 103
  • 1
  • 8

1 Answers1

0

That's not actually an object constructor, so it won't create the this scoping that you require. Therefore, when the setTimeout is called, this refers to the window object, which doesn't contain the object properties you're referencing...

Try creating the object as follows:

function NewsRotator() { ... }

Then instantiating one with new:

var newsRotator = new NewsRotator();

Then, the this keyword is scoped to that particular instance.

Community
  • 1
  • 1
chrisfrancis27
  • 4,516
  • 1
  • 24
  • 32