问题描述
预期行为:
对于 i = 0,打印语句在 0 秒后调用.
For i = 0, print statement called after 0 second .
对于 i = 1,print 语句在 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 中不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!