2

I'm modifying the lovely jquery.carousel.js plugin to have an autochange feature. I want to use setInterval() to call a function, but I can't get it to play nice.

Here is the code I have at the moment:

autoSwitch: function()
{
    if(runAuto)
    {
        $('.next').click();
    }
},
init: function(el, options) {
    if(this.options.auto)
    {
        setInterval("this.('autoSwitch')", this.options.autoTime);
    }
}

This is just a snippet and there is other stuff, but I've left the important bits in. The line I'm having trouble with is setInterval("this.('autoSwitch')", this.options.autoTime);. Whatever I try in the first argument of setInterval, it just doesn't work. So. Can you awesome people help me out as to how I call autoSwitch() from the setInterval() function please?

1 Answer 1

5

I think you're looking for jQuery.proxy:

init: function(el, options) {
    if(this.options.auto)
    {
        // Give `setInterval` a function to call
        setInterval(jQuery.proxy(this.autoSwitch, this)), this.options.autoTime);
    }
}

jQuery.proxy ensures that the function gets called with the correct context (this value). More about this general concept here: You must remember this

That's jQuery-specific. If you want a more general solution, you can use a closure:

init: function(el, options) {
    var context = this;    // Remember what `this` is in a variable
    if(this.options.auto)
    {
        // Give `setInterval` a function to call
        setInterval(function() {
            // The function is a closure that has access to
            // `context`, and so we can call it
            context.autoSwitch();
        }, this.options.autoTime);
    }
}

That uses a closure to bind the context (see: Closures are not complicated), which is the usual way to do this. jQuery.proxy just does a closure behind the scenes in a well-controlled environment so you know it's not closing over more data than you want it to.

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you! Just what I was looking for. The general solution is great too, but not necessary for what I'm doing though :-) Thanks again.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.