问题描述
预期行为:
对于i = 0,在0秒后调用print语句.
For i = 0, print statement called after 0 second .
对于i = 1,在1.1秒后调用打印语句
For i = 1, print statement called after 1.1 seconds
对于i = 2,在2.2秒后调用打印语句
For i = 2, print statement called after 2.2 seconds
实际行为:
分别在0、1、2、3秒之后调用的打印语句,即内部延迟功能被忽略.
Print statement called after 0, 1, 2, 3 seconds respectively i.e. inner delay function is ignored.
那为什么会有差异呢?
So why the discrepancy?
for i in 0...3 {
DispatchQueue.main.asyncAfter(deadline: .now() + .seconds(i), execute: {
DispatchQueue.main.asyncAfter(deadline: .now() + .seconds(i/10), execute: {
print("function was called")
})
})
}
推荐答案
有很多方法可以做到这一点.这里是3:
There are a number of ways you could do this. Here are 3:
使用计时器每秒重复一次块
var i = 0
Timer.scheduledTimer(withTimeInterval: 1, repeats: true) { timer in
i += 1
print("hello \(i)")
if i == 5 {
timer.invalidate()
}
}
调度多个异步任务
for i in 1...5 {
DispatchQueue.main.asyncAfter(deadline: .now() + .seconds(i)) {
print("hello \(i)")
}
}
注意:这会将所有任务预先排入队列,如果有大量任务,则可能会使队列溢出.
Note: This queues all of the tasks up front and could overflow a queue if there were a large number of them.
在后台运行循环并进入睡眠状态,然后切换到前台进行打印
DispatchQueue.global().async {
for i in 1...5 {
sleep(1)
DispatchQueue.main.async {
print("hello \(i)")
}
}
}
注意:如果循环中的工作要花费大量时间,这会稍微漂移(相隔1秒).
Note: This will drift a little (not be 1 second apart) if the work in the loop takes a significant amount of time.
这篇关于为什么将DispatchQueue延迟函数放在另一个DispatchQueue中对Swift没有影响的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!