2017-07-29 141 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