如何制作至少需要一定时间才能完成的功能

How to make a function that takes at least a certain amount of time to 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
}

我使用 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;
    });
  }
}