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.
setInterval
expects a function.this.func1
is 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);
thensetInterval
will call the correct function, butthis
will 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:With parentheses, you're invoking the method, not setting it as a callback.
setInterval(this.func1(), 1000);
func1 won't be executed in the scope of
this
, so it won't have access to func2. I'm a bit rusty, but you should be able to use call(). I don't recall if you need to call() from init and func1, or just within func1.Thats because when you use
setInterval
, the first argument must be a reference to a funcion:It's without parentheses because
this.func1()
means that functionthis.func1
is executed. Andthis.func1
is the name of the function, which you can use as a reference.