skip to Main Content

I have a function which periodically checks a condition and I want the function to ONLY proceed once the condition is met. This seems like such a basic task, but for some reason I cannot find a good way to solve this.

When I call the function below, I always get ‘job not done yet’ first and then after three seconds ‘job done’. How can I make it proceed to the return statement only after the counter == 3 ?
Sorry if this is such a noob thing to ask. I used Google, I promise, but to no avail.

Future<String> delayTest() async {
    var counter = 0;
    await Timer.periodic(const Duration(seconds: 1), (timer) {
      counter++;
      if (counter == 3) {
        print('job done');
        timer.cancel();
      }
    });
   
    return ('job not done yet.');
  }

2

Answers


  1. You should wait until timer gets canceled. Something like this:

    Future<String> delayTest() async {
      var counter = 0;
      const duration = Duration(seconds: 1);
      final timer = Timer.periodic(duration, (timer) {
        counter++;
        print('not done yet');
        if (counter == 3) {
          print('job done');
          timer.cancel();
        }
      });
      while (timer.isActive) {
        // waiting for the same time duration to check if timer is still active after it
        await Future.delayed(duration);
      }
      return 'done';
    }
    
    Login or Signup to reply.
  2. If you want to wait 3 seconds
    You can use

    Future<String> delayTest() async {
       await Future.delayed(Duration(seconds: 3));
    
       return ('job not done yet.');
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search