问题描述
我一直在尝试在自重复计时器上创建一两秒的延迟.这就是我创建计时器的方式:
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)
所以计时器不断地运行方法updatePosition().但是,我在该方法中有一个 if 语句,我希望将计时器延迟几秒钟:
So the timer constantly runs the method 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 distance <= respawnDistance * 0.1 {
// Delay timer for 1 second
}
我当时认为我可以做到这一点:
And I was thinking that I could do this:
currentThread.invalidate()
然后只需创建另一个在 1 秒后运行的计时器,这会导致重新激活前一个计时器.但是,我认为如果有办法让当前的 Timer 休眠,那效率会很低吗?
And then just create another Timer that runs after 1 second, which leads to the reactivation of the previous timer. However, I think that would be inefficient if there is a way to sleep the current Timer?
推荐答案
NSTimer
不是那么准确.它的最大分辨率约为 50 - 100 毫秒.无论如何,您可以添加一个变量来控制计时器的触发:
NSTimer
is not that accurate. Its maximum resolution is somewhere around 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
}
这篇关于在 Swift 中休眠或延迟 Timer 线程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!