setInterval only runs once on object method

2019-07-06 10:55发布

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.

3条回答
萌系小妹纸
2楼-- · 2019-07-06 11:34

setInterval expects a function. this.func1 is a function but this.func1() is the result of calling the function, which is undefined (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); then setInterval will call the correct function, but this 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:

this.init = function() {
    var self = this;
    setInterval(function() { self.func1(); }, 1000);
};
查看更多
该账号已被封号
3楼-- · 2019-07-06 11:40

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.

查看更多
Juvenile、少年°
4楼-- · 2019-07-06 11:49

Thats because when you use setInterval, the first argument must be a reference to a funcion:

setInterval(this.func1, 1000);

It's without parentheses because this.func1() means that function this.func1 is executed. And this.func1 is the name of the function, which you can use as a reference.

查看更多
登录 后发表回答