【问题标题】:How to simulate long time process (sleep) in Dart?如何在 Dart 中模拟长时间的过程(睡眠)?
【发布时间】:2015-06-21 08:53:52
【问题描述】:

我想停止/休眠执行以模拟长时间的过程,不幸的是我找不到有关它的信息。我已阅读以下主题 (How can I "sleep" a Dart program),但这不是我想要的。

例如,dart:io 包中的 sleep() 函数不适用,因为此包在浏览器中不可用。

例如:

import 'dart:html';
main() {
  // I want to "sleep"/hang executing during several seconds
  // and only then run the rest of function's body
  querySelect('#loading').remove();
  ...other functions and actions...
}

我知道有Timer类在一段时间后进行回调,但它仍然不妨碍整个程序的执行。

【问题讨论】:

    标签: dart dart-async


    【解决方案1】:

    没有办法停止执行。您可以使用 Timer 或 Future.delayed 或仅使用仅在经过一定时间后才结束的无限循环。

    【讨论】:

    • 谢谢Gunter,我喜欢这样的答案)严格、惯用且简单
    【解决方案2】:

    如果你想要一个停止世界睡眠的功能,你可以完全自己做。我会提到我不建议你这样做,阻止世界是一个非常糟糕的主意,但如果你真的想要它:

    void sleep(Duration duration) {
      var ms = duration.inMilliseconds;
      var start = new DateTime.now().millisecondsSinceEpoch;
      while (true) {
        var current = new DateTime.now().millisecondsSinceEpoch;
        if (current - start >= ms) {
          break;
        }
      }
    }
    
    void main() {
      print("Begin.");
      sleep(new Duration(seconds: 2));
      print("End.");
    }
    

    【讨论】:

    • 非常有趣的方法!)谢谢你的建议!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-05-15
    • 2021-09-05
    • 1970-01-01
    • 2023-04-10
    • 2021-05-29
    • 1970-01-01
    • 2015-06-28
    相关资源
    最近更新 更多