我正在使用计时器以定时顺序显示数组的元素。我想更改或“扰动”计时器以使其更自然。有什么方法可以使用随机变量或其他方法来改变或扰乱时间计数。
这是使用计时器的代码:
let strings = [["First down. Run up the middle","run"],["Second down. Screen pass, incomplete","pass"],["Third down. Incomplete pass","pass"],["Fourth down. Punt","punt"],
var timer = Timer.scheduledTimer(withTimeInterval: 2, repeats: true){ t in
speaking = names[count][1]
//delay here using a random variable.
let delta = Int(arc4random_uniform(10))/8
//Following line does not compile and gives error
//Type of expression is ambiguous without more context
DispatchQueue.main.asyncAfter(deadline: .now() + delta) {
self.post(self,strings[count][0])
}
count += 1
if count >= num {
t.invalidate()
}
}
答案 0 :(得分:1)
您可以以比所需的实际间隔快一些的速度运行计时器,然后在其中包含一些if
语句,该语句(通过随机变量或您想要实现)决定是实际触发还是触发继续下一次触发计时器。
var timer = Timer.scheduledTimer(withTimeInterval: 20, repeats: true){ t in
if self.shouldDoTheThingAgain() {
self.doTheThing()
}
}
假设您有一些方法可以跟踪已完成该操作的次数(例如,通过某个属性),而实际执行了您想做的事情。