Here is the code.
(function($){
$.fn.testfunc = function() {
this.init = function() {
setInterval(this.func1(), 1000);
};
this.func1 = function() {
console.log('func1');
this.func2();
};
this.func2 = function() {
console.log('func2');
//some codes
};
return this.init();
}
})(jQuery);
*When I use parenthesis the 1st and 2nd method runs but the 1st method is called only once.
*When I don’t use parenthesis the 1st method runs in interval just fine but it doesn’t/couldn’t call the 2nd method.
What should I go with? With parenthesis or not? I need to run the 1st method in the interval but also need to call 2nd method.
setIntervalexpects a function.this.func1is a function butthis.func1()is the result of calling the function, which isundefined(the function doesn’t return anything). This is your first misunderstanding.The second misunderstanding has to do with scope. If you call
setInterval(this.func1, 1000);thensetIntervalwill call the correct function, butthiswill not refer to what you think. I don’t have time now to explain and you should definitely read more about this. In any case, this will work: