[英]Sleep or delay a Timer thread in Swift
I have been trying to create a delay of one or two seconds on a self repeating timer. 我一直试图在自重复计时器上创建一到两秒的延迟。 This is how I create the timer:
这是我创建计时器的方式:
currentThread = Timer.scheduledTimer(timeInterval: 0.001, target: self, selector: #selector(Movement.updatePosition), userInfo: nil, repeats: true)
So the timer constantly runs the method updatePosition(). 因此,计时器会不断运行updatePosition()方法。 However, I have an if statement within that method where I would like to have the timer be delayed for a few seconds:
但是,我在该方法中有一个if语句,希望将计时器延迟几秒钟:
if distance <= respawnDistance * 0.1 {
// Delay timer for 1 second
}
And I was thinking that I could do this: 我当时想我可以做到这一点:
currentThread.invalidate()
And then just create another Timer that runs after 1 second, which leads to the reactivation of the previous timer. 然后只需创建另一个在1秒钟后运行的计时器,即可重新激活前一个计时器。 However, I think that would be inefficient if there is a way to sleep the current Timer?
但是,我认为如果有一种方法可以使当前Timer休眠,那么效率会很低?
NSTimer
is not that accurate. NSTimer
不够准确。 Its maximum resolution is somewhere around 50 - 100ms. 其最大分辨率约为50-100ms。 Anyhow, you can add a variable to control the firing of the timer:
无论如何,您可以添加一个变量来控制计时器的触发:
var doNotUpdate = false
if distance <= respawnDistance * 0.1 {
doNotUpdate = true
DispatchQueue.main.asyncAfter(deadline: .now() + 1.0) {
doNotUpdate = false
}
}
func updatePosition() {
if doNotUpdate { return }
// update your position
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.