我如何在.forEach互动中暂停一下 [英] How would I put a pause in a .forEach interation
问题描述
我正试图在forEach循环之间添加一个暂停列表.
I am attempting to put in a pause between a forEach loop for a list.
我本以为超时会导致循环暂停,但似乎一次只能启动3个计时器. (非常连续).
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?
推荐答案
使用await Future.delayed()
暂停一定的持续时间并进行for循环,而不是forEach()
Use await Future.delayed()
to pause for certain duration and a for loop, instead of forEach()
如果forEach()
接收异步函数,则每个迭代调用将在单独的异步上下文中运行,其原因类似于并行代码执行.同时forEach它自己将立即返回,而无需等待任何异步功能完成.
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.
样本: 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');
};
}
这篇关于我如何在.forEach互动中暂停一下的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!