延迟循环(倒数计时功能) [英] Delaying the loop (countdown func)
问题描述
我看了很多文章,没有一个答案是正确的。我知道这些方法有效,但是在for循环中却无效。如何创建倒计时功能-在其中可以延迟一秒打印数组。
I've looked at many articles, none of the answers are correct. I know that these methods work, but inside a for-loop they don't. How can I create a countdown func - where I can print an array with a one second delay in between.
let array = [9, 8, 7, 6, 5, 4, 3, 2, 1]
我尝试过:
for n in array {
DispatchQueue.main.asyncAfter(deadline: .now() + 1) {
print(n)
}
}
它会打印1秒后所有数字。因此,我尝试了以下操作:
And it prints all the numbers after 1 second. So I tried this:
override func viewDidLoad() {
super.viewDidLoad()
let timer = Timer.scheduledTimer(timeInterval: 2, target: self, selector: (#selector(printer)), userInfo: nil, repeats: true)
}
@objc func printer() {
for n in array {
print(n)
}
}
相同的结果。我猜这些是好的方法,但是出了点问题。
Same result. I guess these are good methods, but something's wrong.
推荐答案
为计时器创建一个计数器变量和另一个变量
Create a counter variable and another variable for the timer
var counter = 0
var timer : Timer?
在 viewDidLoad
中创建计时器
override func viewDidLoad() {
super.viewDidLoad()
timer = Timer.scheduledTimer(timeInterval: 1.0, target: self, selector: #selector(printer), userInfo: nil, repeats: true)
}
在操作方法中,增加 counter
变量,如果达到数组中的项目数,则使计时器无效。
In the action method increment the counter
variable and invalidate the timer if the number of items in the array is reached.
@objc func printer() {
print(array[counter])
counter += 1
if counter == array.count {
timer?.invalidate()
timer = nil
}
}
另一种方法是 DispatchSourceTimer
,它避免了 @objc
运行时
Another way is DispatchSourceTimer
, it avoids the @objc
runtime
var timer : DispatchSourceTimer?
let interval : DispatchTime = .now() + .seconds(1)
timer = DispatchSource.makeTimerSource(queue: DispatchQueue.global())
timer!.schedule(deadline:interval, repeating: 1)
var index = 0
timer!.setEventHandler {
// DispatchQueue.main.async {
print(array[index])
}
index += 1
if index == array.count {
timer!.cancel()
timer = nil
}
}
timer!.resume()
这篇关于延迟循环(倒数计时功能)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!