我正在构建一个获取传感器值的应用程序。每次传感器值发生变化时,都会调用 handleDeviceMotionUpdate 函数,每秒调用多次。
handleDeviceMotionUpdate 调用不同类的以下函数:
func doStuff(){
delay(1){
print("some thing")
}
}
延迟函数看起来像这样,这是我在 Stackoverflow 的某个地方找到的:
func delay(_ delay:Double, closure:@escaping ()->()){
let when = DispatchTime.now() + delay
DispatchQueue.main.asyncAfter(deadline: when, execute: closure)
}
我预计“some thing”只会在一秒后打印出来,但我认为问题在于每秒多次调用 doStuff()。有什么方法可以在每秒调用多次的函数中延迟一定时间后执行代码?为什么我的示例不起作用?
我考虑过在第一个类中创建一个 bool 变量,该变量在 1 秒后设置为 true,然后调用不同类的函数,但我认为这可能会使我的代码困惑,因为我已经在其他地方做过了。
最佳答案
为此声明一个全局计时器:
var timer: Timer = Timer(timeInterval: -1, target: self, selector: #selector(ViewControllerName.doStuff), userInfo: nil, repeats: false)
其中 ViewControllerName
是将 doStuff()
作为方法的类的名称。
确保最初使计时器无效(如在 viewDidLoad()
中):
timer.invalidate()
下面是您的 doStuff()
的样子:
func doStuff() {
//As long as the timer is started/vlaid, nothing will be executed
if !timer.isValid {
//print something or do whatever you'd like
print("some thing ", Date())
//and finally restart the timer
timer = Timer.scheduledTimer(
timeInterval: 1, //This is the time interval you don't want to do nothing
target: self,
selector: #selector(ViewController.doStuff),
userInfo: nil,
repeats: false)
}
}
关于swift - 每秒调用多次的函数中的延迟代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52083821/