0

I have implemented a timer function in angularjs application as following:

$timeout($scope.startFilling, 30000)
    $scope.onTimeout = function(){

        $scope.counter1--; <= counter1 is initialized to 3
        mytimeout = $timeout($scope.onTimeout,1000);

        if($scope.counter1==0){
            $timeout.cancel(mytimeout);
            $scope.counter1=0
        }
    }

    var mytimeout = $timeout($scope.onTimeout,1000);

I am basically calling a function after 30 seconds and the counter goes from 30 towards 0 and at 0 I cancel the timer.

I tried to implement it in angular2 as following:

start(){

        let timer = Observable.timer(3000,1000);
        this.myCounter = timer.subscribe(t=> this.startFilling(t));

    }

    startFilling(counter){

        this.counter1=--counter;
        if(this.counter1==0){

        this.myCounter.unsubscribe();
    }

    } 

But this isn't totally working correct. I am binding counter1 (which is initialized to 3)on my template. start() function is called a button click and as soon as it is called, I want to decrease the counter1 from 3 to 0 and after 3 seconds I want to call startFilling() function. How can I do it?

5
  • this.myCounter.unsubscribe() should cancel the timer ? shouldnt it ? whats the problem Commented Mar 6, 2017 at 13:39
  • I understood the unsubscribe part, but the counter value (counter1 which I am showing on template) is not being handled correctly somehow. I have initialized it to 3 and I expect it to go down till 0 and then end. Commented Mar 6, 2017 at 13:45
  • can u create plunkr or something ?? Commented Mar 6, 2017 at 13:49
  • I also updated my question to be more descriptive Commented Mar 6, 2017 at 13:50
  • plnkr.co/edit/TV24p7PdLK7JPdZq3fZ1?p=preview Commented Mar 6, 2017 at 14:02

2 Answers 2

1

Subtract one from the counter, unsubscribe when it reaches 0:

  tickerFunc(tick){
    this.counter1 = this.counter1 - 1;

     if(this.counter1==0){

      this.counter.unsubscribe();
    }
  }

Demo

Sign up to request clarification or add additional context in comments.

Comments

0

The counter is 0 based so you are setting counter1 to -1 and then 0. It is probably just easier to decrement counter1 by 1 each time in the subscription.

1 Comment

Could you perhaps show the code snippet how do suggest it? This is what I tried: plnkr.co/edit/TV24p7PdLK7JPdZq3fZ1?p=preview

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.