setInterval in setTimout 在 angularjs 控制器中只触发一次

setInterval in setTimout only firing once in angularjs controller

本文关键字:一次 setTimout in angularjs 控制器 setInterval      更新时间:2023-09-26

正如标题所述,这似乎只触发一次。 我需要它持续运行。

控制器中的代码:

    setTimeout(function () {
        $scope.test();
        console.log('starting test');
        // check and update dates every minute (hopefully language will be in the bridge)
        $scope.testInterval = setInterval($scope.test(), 1000);
    }, 2000);
    $scope.test = function () {
        console.log('test');
    };

控制台输出:

test
starting test
test

然后什么都没有。只是停止工作。

你在 setinterval 行中调用 scope .test()。您需要传递函数而不是函数的结果。

$scope.testInterval = setInterval($scope.test(), 1000);

成为

$scope.testInterval = setInterval($scope.test, 1000);

此外,由于 setInterval 在第一次触发时立即触发,因此在设置间隔之前不需要额外的 $scope.test()。

由于您正在调用该函数,因此您应该使用

$scope.testInterval = setInterval($scope.test, 1000);

这里应该注意的区别是$scope.test没有括号(),因为您要调用此函数而不是此函数的执行返回值。

如果您已经编写了$scope.test()它将返回未定义,并且您的间隔将不会运行(因为您的 setInterval 函数参数未定义)。如果您编写$scope.test则间隔将调用测试函数。

使用 $interval 而不是 setInterval

var interval = $interval(function() {
  console.log('say hello');
}, 1000);

如果要停止它:

$interval.cancel(interval);