Ajv2324
Ajv2324

Reputation: 522

What is wrong with this $interval? Only fires on page load

setTimeout(function(){
    userIsSetup = true;
    console.log('This happened!');
}, 4000);

$interval(function(){
    if(userIsSetup){
        $scope.received = true;
        $interval.cancel(); // Can pass a promise into this as well
    }
    console.log('A second has passed');
}, 1000, 30);

This is sort of a test for future functionality, but basically I just want to check to see if something is done once a second for thirty seconds. If it is done, stop the timer and turn on a variable so that something on the page disappears, otherwise after thirty seconds tell the user something was gonna take some time.

As the title says, the console log in the interval only happens once, when the page loads, and then doesn't happen again. Do I need to start the timer in some way or something?

Upvotes: 1

Views: 144

Answers (1)

Deep
Deep

Reputation: 9794

try with something like this.

 $scope.userIsSetup = false;
 $interval = setInterval(function(){
 $scope.check();
console.log('This happened!');
},2000);


$scope.check = function(){
        if($scope.userIsSetup){
            $scope.received = true;
            $interval.cancel(); 
        }
        console.log('2 second has passed');

   };

For the $interval in angular

app.controller('MainCtrl', function($scope,$interval) {


$scope.totalTimepassed = 0;


$scope.callAtInterval =  function () {

if($scope.totalTimepassed < 9)
{
$scope.totalTimepassed = $scope.totalTimepassed +1;
console.log($scope.totalTimepassed +" seconds passed");
}
else
{  
   $interval.cancel(interval);
   console.log("10 seconds passed");
}

}

var interval =  $interval($scope.callAtInterval, 1000);



});

Upvotes: 1

Related Questions