AngularJS中是否存在竞争条件?

时间:2014-03-12 23:38:14

标签: javascript angularjs

我正在编写一个控制器,结果导致用户的操作在$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;
 }

}

据我所知,只有一个线程正在运行,但哪些操作是原子的?

1 个答案:

答案 0 :(得分:-1)

正如您所说,Javascript是单线程的,因此不存在同时改变同一对象的风险。你的超时功能和你的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);
}