Search code examples
flutterdartasynchronoustimer

How to make a function that takes at least a certain amount of time to complete


I want to have a function that will always take a minimum amount of time.

For example, the async function that depends on some sort of async code should always atleast take a certain time, even if the async code inside the function is complete.

Future<String> function1(prop) async {
  // Set a minimum time
  // Start a timer

  // await async code

  // Check to see if timer is greater then minimum time
  // If so, return
  // Else, await until minimum time and then return
}

Solution

  • I was able to solve this using Stopwatch and Future.Delayed.

    Future<dynamic> functionThatAlwaysTakesAtleastHalfASecond(prop) async {
      // Start a stopwatch
      Stopwatch stopwatch = new Stopwatch();
      
      // Set a minimum time
      int delayTime = 500;
      stopwatch.start();
    
      // await async code
      final result = await functionThatTakesLessThenHalfASecond(prop);
    
      // Check to see if timer is greater then minimum time
      // If so, return
      if (stopwatch.elapsedMilliseconds > delayTime) {
        return result;
      } 
      // Else, await until minimum time and then return
      else {
        return await Future.delayed(Duration(milliseconds: delayTime - stopwatch.elapsedMilliseconds),
            () {
          return result;
        });
      }
    }