简体   繁体   English

setInterval仅在对象方法上运行一次

[英]setInterval only runs once on object method

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. 我需要在区间中运行第一个方法,但也需要调用第二个方法。

Thats because when you use setInterval , the first argument must be a reference to a funcion: 那是因为当你使用setInterval ,第一个参数必须是对funcion的引用:

setInterval(this.func1, 1000);

It's without parentheses because this.func1() means that function this.func1 is executed. 它没有括号,因为this.func1()表示执行函数this.func1 And this.func1 is the name of the function, which you can use as a reference. this.func1是函数的名称,您可以将其用作参考。

setInterval expects a function. setInterval需要一个函数。 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.func1是一个函数,但this.func1()是调用函数的结果,该函数undefined (函数不返回任何内容)。 This is your first misunderstanding. 这是你的第一个误解。

The second misunderstanding has to do with scope. 第二个误解与范围有关。 If you call setInterval(this.func1, 1000); 如果你调用setInterval(this.func1, 1000); then setInterval will call the correct function, but this will not refer to what you think. 随后setInterval会调用正确的功能,但是this将不是指你的想法。 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);
};

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. FUNC1不会的范围内执行this ,所以不会有机会获得FUNC2。 I'm a bit rusty, but you should be able to use call(). 我有点生疏,但你应该可以使用call()。 I don't recall if you need to call() from init and func1, or just within func1. 我不记得你是否需要从init和func1调用(),或者只需要在func1中调用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM