2017-07-29 192 views
1

的事情是我想的隨機數添加到一個變量,它最初是0,這具有直到變量達到100在隨機時間間隔

$scope.var1 = 0; 

do{ 
    $timeout(function(){ 
     $scope.var1 += Math.floor(Math.random() * 100 +1); 
    },Math.floor(Math.random() * 100 +1)); 
    console.log($scope.var1); 

}while($scope.var1<100) 

$scope.var1始終保持一個隨機超時發生後,添加隨機數0,因此它進入無限循環;

+4

所以呢?你的問題是什麼? – Kamesh

+0

剛纔編輯的問題 – chows2603

回答

3

你得到inifinity環路自$timeout功能,您使用的是異步的,但你的循環是同步。你必須使用遞歸:

$scope.var1 = 0; 

function recursiveTimeout(){ 
    $timeout(function(){ 
     if($scope.var1 < 100){ 
      $scope.var1 += Math.floor(Math.random() * 10 + 1); 
      console.log($scope.var1); 
      recursiveTimeout() 
     } 
    }, Math.floor(Math.random() * 1000 + 1)); 
} 
recursiveTimeout() 

http://jsfiddle.net/dwypcx1f/3/

+0

完美!非常感謝 :) – chows2603

-2

Math.random是一個JS的功能,所以它必須是Math.floor(Math.random() * 100 +1);代替Math.floor(Math.random * 100 +1);

我沒有檢查你的代碼的其餘部分。


您在每次循環迭代中開始一個新循環。我不知道正確的語法AngularJS,因爲我喜歡Angular2,但這樣的事情應該工作...

$scope.var1 = 0; 
var repeatFunc = function repeatFunc() { 
    var num = Math.floor(Math.random() * 100 +1); 
    $scope.var1 += num; 
    console.log("num: ", num); 
    if ($scope.var1 < 100) 
     $timeout(repeatFunc, num); 
} 
repeatFunc(); 
+0

編輯我的問題 – chows2603