setInterval仅在对象方法上运行一次 [英] setInterval only runs once on object method

查看:62
本文介绍了setInterval仅在对象方法上运行一次的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下是代码。



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

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.

第二个误解与范围有关。如果你调用 setInterval(this.func1,1000); 然后 setInterval 将调用正确的函数,但不会引用您的想法。我现在没时间解释,你一定要详细了解这个。在任何情况下,这都可行:

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);
};

这篇关于setInterval仅在对象方法上运行一次的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆