0

I am using below code to start the timer

Timer Snippet:

 _increamentCounter() {
    Timer.periodic(Duration(seconds: 2), (timer) {
       setState(() {
         _counter++;
       });
    });
  }


 RaisedButton raisedButton =
        new RaisedButton(child: new Text("Button"), onPressed: () {
            _increamentCounter();
        });

What I all want is to stop this timer after specific(N) timer interval.

Jitesh Mohite
  • 31,138
  • 12
  • 157
  • 147
  • Your question title says that you want to *stop* the `Timer`, but later you say that you want to *start* the `Timer`. Which is it? – jamesdlin Aug 29 '19 at 04:44

3 Answers3

1

Since you want to cancel the Timer after a specific number of intervals and not after a specific time, perhaps this solution is more appropriate than the other answers?

Timer _incrementCounterTimer;


_incrementCounter() {
    _incrementCounterTimer = Timer.periodic(Duration(seconds: 2), (timer) {     
        counter++; 

        if( counter == 5 ) // <-- Change this to your preferred value of N
            _incrementCounterTimer.cancel();

        setState(() {});
    });
}


 RaisedButton raisedButton = new RaisedButton(
    child: new Text("Button"), 
    onPressed: () { _incrementCounter(); }
 );
Magnus
  • 17,157
  • 19
  • 104
  • 189
0

You can use a Future.delayed.

Future.delayed(const Duration(seconds: n), () => _increamentCounter());
Rodrigo Bastos
  • 2,230
  • 17
  • 17
0

Alternatively to Future.delayed(), you can also use

Timer(const Duration(seconds: n), () => _increamentCounter());

The Timer class exposes a couple extra methods like .cancel(), .tick, and isActive, so prefer it if you see yourself needing them down the road.