javascript 在 AngularJS 中立即启动 $interval

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/21989791/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 22:10:32  来源:igfitidea点击:

Start $interval immediately in AngularJS

javascriptjqueryangularjs

提问by alexP

I have the function notifications.get()that runs every 10 seconds.

我有notifications.get()每 10 秒运行一次的功能。

function notificationsCtrl($scope, $interval) {
    $interval(function(){ 
        $scope.notification = notifications.get();
        $('.card').addClass('rotate');
    }, 10000);
};

But when the page is loaded, the function should be called once immediately. Can anyone help me?

但是当页面加载时,该函数应该立即调用一次。谁能帮我?

回答by Pranav C Balan

You can do it like this,

你可以这样做,

  1. Define it as a function
  2. Call it immediately by function name
  3. Attach function to $interval()for execute in every 10 sec.
  1. 将其定义为函数
  2. 通过函数名立即调用
  3. 将函数附加到$interval()for 每 10 秒执行一次。

CODE:

代码:

function notificationsCtrl($scope, $interval) {
    var fun = function(){ 
        $scope.notification = notifications.get();
        $('.card').addClass('rotate');
    };
    fun();
    $interval(fun, 10000);
};

回答by Zhen StackOverflow

you can use $interval.flush(millis) to move forward by millis milliseconds and trigger any functions scheduled to run in that time.

您可以使用 $interval.flush(millis) 以毫秒为单位向前移动并触发计划在该时间内运行的任何函数。