You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何让使用await的refreshState递归函数运行1秒后自动停止

解决方案

你不需要改动原有递归逻辑,只需要新增一个1秒的计时器,超时后自动将isPlaying置为false即可终止递归循环,具体实现步骤如下:

  • 在当前State类中声明计时器变量,用于控制超时逻辑:
// 原有控制递归的变量
bool isPlaying = false;
// 新增超时计时器变量
Timer? _refreshTimer;
  • 修改refreshState方法,首次调用时启动1秒超时计时器:
Future<dynamic> refreshState() async {
  // 首次调用时初始化计时器,1秒后自动终止循环
  if (_refreshTimer == null) {
    _refreshTimer = Timer(const Duration(seconds: 1), () {
      isPlaying = false;
      _refreshTimer?.cancel();
      _refreshTimer = null;
    });
  }

  setState(() {});
  await Future<dynamic>.delayed(animDuration + const Duration(milliseconds: 50));
  if (isPlaying) {
    await refreshState();
  }
}
  • 在dispose生命周期中销毁计时器,避免内存泄漏和页面销毁后报错:
@override
void dispose() {
  _refreshTimer?.cancel();
  super.dispose();
}

注意:调用refreshState方法前需要先将isPlaying置为true,才会正常进入递归循环。如果你的动画单帧间隔animDuration波动较大,也可以额外记录方法启动时间,每次递归前校验时间差,避免极端场景下超时不准的问题。

内容的提问来源于stack exchange,提问作者sea

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.01 20:39:01