3

I am attempting to put in a pause between a forEach loop for a list.

I would have thought the timeout would cause a pause for the loop but it just seems to start 3 timers all at once. (In very quick succession.)

  startTimeout(int seconds) async {
    print('Timer Being called now');
    var duration = Duration(seconds: seconds);
    Timer(duration, doSomething());
  }


  startDelayedWordPrint() {
    List<String> testList = ['sfs','sdfsdf', 'sfdsf'];
    testList.forEach((value) async {
      await startTimeout(30000);
      print('Writing another word $value');
    });
  }

Any idea how I might do this?

Yonkee
  • 1,781
  • 3
  • 31
  • 56

1 Answers1

13

Use await Future.delayed() to pause for certain duration and a simple old for(...in...){} loop, instead of forEach() to iterate the values.

If forEach() receives async functions, each iteration call will run in a separate asynchronous context which can be reasoned about similarly to parallel code execution. Meanwhile forEach it self will return immediately without waiting until any async function to complete.

How to Async/await in List.forEach() in Dart

Sample: https://dartpad.dartlang.org/a57a500d4593aebe1bad0ed79376016c

main() async {
    List<String> testList = ['sfs','sdfsdf', 'sfdsf'];
    for(final value in testList) {
      await Future.delayed(Duration(seconds: 1));
      print('Writing another word $value');
    };
  }
Ski
  • 14,197
  • 3
  • 54
  • 64
  • Tried both for (var in list) and for (int i = 0; list.length; i+) both just trigger the timer all the time and neither allow me to use await Do you have a code sample? – Yonkee Jan 24 '19 at 06:14
  • That link is about async, thats not the issue. The issue is that I need a pause in each iteration. – Yonkee Jan 24 '19 at 06:17
  • @Yonkee added sample with `Future.delayed()`, if this is what you're looking for? – Ski Jan 24 '19 at 06:20
  • That's the ticket. Thanks – Yonkee Jan 24 '19 at 06:39