Javascript 按随机时间间隔添加随机数

Javascript 按随机时间间隔添加随机数,javascript,angularjs,random,Javascript,Angularjs,Random,问题是我想给一个变量加上一个随机数,这个变量最初是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

问题是我想给一个变量加上一个随机数,这个变量最初是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;
做{
$timeout(函数(){
$scope.var1+=Math.floor(Math.random()*100+1);
},Math.floor(Math.random()*100+1));
log($scope.var1);

}而($scope.var1
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();
$scope.var1=0;
var repeatFunc=函数repeatFunc(){
var num=Math.floor(Math.random()*100+1);
$scope.var1+=num;
log(“num:,num”);
如果($scope.var1<100)
$timeout(repeatFunc,num);
}
repeatFunc();

由于您使用的
$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()
$scope.var1=0;
函数recursiveTimeout(){
$timeout(函数(){
如果($scope.var1<100){
$scope.var1+=Math.floor(Math.random()*10+1);
log($scope.var1);
递归超时()
}
},Math.floor(Math.random()*1000+1));
}
递归超时()

那么?你的问题是什么?刚刚编辑了这个问题