【问题标题】:AngularJS: I can repeatly call a function with some time interval?AngularJS:我可以重复调用某个时间间隔的函数吗?
【发布时间】:2016-04-04 13:17:33
【问题描述】:

有什么方法可以重复调用 angularjs 中的函数。我在我的控制器中使用它:

$interval( $rootScope.synchronization(), 1000 ); 

但它只调用一次同步函数。

【问题讨论】:

    标签: javascript angularjs timer intervals repeat


    【解决方案1】:

    去掉括号:

    $interval( $rootScope.synchronization, 1000 ); 
    

    使用括号传递调用会执行函数,然后将结果作为参数传递给 $interval。如果没有括号,您实际上会传递方法本身。

    【讨论】:

      【解决方案2】:

      使用括号,您只是调用它,而不是传递对函数的引用。

      $interval( $rootScope.synchronization, 1000 ); 
      

      【讨论】:

        【解决方案3】:

        在 Angular 的 $interval 中。 fn 函数每延迟毫秒执行一次:

        $interval(fn, delay, [count], [invokeApply], [Pass]);
        

        例如,试试这个:

        $scope.myVariable = 1;
        $interval( function(){
            $scope.myVariable++;
        }, 1000 ); 
        

        所以$interval上的第一个参数一定是函数,$rootScope.synchronization()不是函数,是对函数的调用。在您的情况下,将 $rootScope.synchronization() 更改为 $rootScope.synchronization

        $interval( $rootScope.synchronization, 1000 );
        

        【讨论】:

        • 您的最后一个示例有一个错误,您在其中创建了匿名函数并且您实际上并没有在其中执行任何操作。它应该是$interval($rootScope.synchronization, 1000);$interval( function(){ $rootScope.synchronization(); }, 1000 );
        • 你是对的,那个代码很糟糕,很抱歉。我会纠正它。谢谢
        猜你喜欢
        • 1970-01-01
        • 2016-04-05
        • 1970-01-01
        • 1970-01-01
        • 2015-05-03
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2023-03-21
        相关资源
        最近更新 更多