AngularJS中存在竞争条件吗?

Do race conditions exist in AngularJS?

本文关键字:条件 竞争 存在 AngularJS      更新时间:2023-09-26

我正在编写一个控制器,最终出现了这样一种情况,即用户的操作改变了$scope上的状态,而$timeout可能同时运行。在AngularJS中,这是一个需要注意的问题吗?下面是代码的简化:

function Ctrl($scope, $timeout) {
 $scope.counter = 0;
 $timeout( function incrementor() {
    $scope.counter += 1;
    $timeout(incrementor, 100);
 }, 100 )

 // Call when user clicks a button
 $scope.onClick = function() {
    $scope.counter += 1;
 }
}

我知道只有一个线程在运行,但是什么操作是原子的?

正如你所说,Javascript是单线程的,所以在同一时间没有改变同一对象的风险。你的timeout函数和onClick函数永远不会在同一时间执行(尽管看起来是这样)。

在这种情况下,你可以在计时器中添加一个安全保护,就像这样:

function Ctrl($scope, $interval) {
    $scope.counter = 0;
    var lastIntervalCounter = $scope.counter;
    $interval(function incrementor() {
        if (lastIntervalCounter == $scope.counter) {
            // Only perform this if the counter hasn't been modified
            // since the last time incrementor was called
            $scope.counter += 1;
        }
        lastIntervalCounter = $scope.counter;
    }, 100);
}