Add a random number to random time intervals

advertisements

The thing is I want to add random number to a variable which is initially 0 which has to happen after a random timeout until the variable reaches 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 always stays 0, hence it goes to an infinite loop;


You get inifinity loop since $timeout function, that you use, is async, but your loop is sync. You have to use recursion:

$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/