0

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);       
};
Shiladitya
  • 12,003
  • 15
  • 25
  • 38
Christy
  • 191
  • 1
  • 4
  • 12
  • it's because of the scope is incorrect. You're `this` inside the `setInterval` is the setInterval itself and not the object. There's a lot of those questions on the stack, try to find the answer there. – Dawid Zbiński Oct 02 '17 at 04:24
  • Possible duplicate of [Javascript setInterval and \`this\` solution](https://stackoverflow.com/questions/2749244/javascript-setinterval-and-this-solution) – Dawid Zbiński Oct 02 '17 at 04:26

2 Answers2

2

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...
    }
}
trgiangvp3
  • 253
  • 3
  • 9
0

Maybe this is because you have write Next() instead of next() Try writing small 'n'.

Hope this will help you

Thanks!!