【问题标题】:How to make a function that takes at least a certain amount of time to complete如何制作至少需要一定时间才能完成的功能
【发布时间】:2021-08-10 21:22:31
【问题描述】:

我想要一个总是花费最少时间的函数。

例如,依赖于某种异步代码的异步函数应该总是至少需要一定的时间,即使函数内部的异步代码是完整的。

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
}

【问题讨论】:

    标签: flutter dart asynchronous timer


    【解决方案1】:

    我能够使用StopwatchFuture.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;
        });
      }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-10-26
      • 1970-01-01
      • 2022-12-23
      • 2015-12-23
      • 2018-02-07
      相关资源
      最近更新 更多