Christy Christy - 3 years ago 173
jQuery Question

How do I call a function from within a nested function in JQuery?

I have the following jQuery code. The this.Next() function is throwing a "is not a function" error when called. The this.Next() function is called within the same function as this.countdown(). How would I call this.Next() inside the setInterval() nested function?

this.countdown = function(element)
{
interval = setInterval(function() {
var el = document.getElementById(element);
if(seconds == 0) {
if(minutes == 0) {
alert(el.innerHTML = "Your time for this section has expired");
clearInterval(interval);

// Send user to the next section
return this.Next();
} else {
minutes--;
seconds = 60;
}
}
if(minutes > 0) {
var minute_text = minutes + ' min';
} else {
var minute_text = '';
}
var second_text = 'sec';
el.innerHTML = 'Your time: ' + minute_text + ' ' + seconds + ' ' + second_text;
seconds--;
}, 1000);

};

Answer Source

this 's value will change depends on the context where it is called. You should try as below (I presume your countdown function is in MyObject )

function MyObject() {
    var self = this; // add this declaration and instead of this key word, you can use self
    self.countdown = function (element) {
        ....blah blah blah...


        return self.Next(); // instead of this.Next(), you use self.Next()
        ....blah blah blah...
    }
}
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download