如何解决快速计时器,直到一定时间后才会再次运行
事实证明这是一个挑战,我想要一个计时器,该计时器可以触发脉冲持续10秒钟,然后有效地阻止其再次运行,直到至少经过1秒钟为止。
这是脉冲的代码,但是如何阻止它再次触发,直到经过1秒为止-我可以在计时器中放置一个计时器吗? 任何帮助将不胜感激。
func pulseOn(on: Bool) {
var pulseCount = 4
Timer.scheduledTimer(withTimeInterval: 0.025,repeats: true)
{ timer in
print("PulseCount: \(pulseCount)")
pulseCount = pulseCount - 1
if pulseCount < 1 {
timer.invalidate()
}
}
}
解决方法
可能是这样。加一布尔;
var runPulse: Bool = false
原始计时器功能:
func pulseOn(on: Bool) {
var pulseCount = 4
Timer.scheduledTimer(withTimeInterval: 0.025,repeats: true)
{ timer in
print("PulseCount: \(pulseCount)")
secondCheck() //new funtion
pulseCount = pulseCount - 1
if pulseCount < 1 {
timer.invalidate()
}
}
}
新功能:
func pulseOn(on: Bool) {
Timer.scheduledTimer(withTimeInterval: 1.0,repeats: false)
{ timer in
self.runPulse = true
}
}
然后,无论您在哪里触发pulseOn函数,都可以添加if语句。
if runPulse {
pulseOn()
}
,
在测量两个事件之间的时间时,请使用0.92.5
及其Date
函数而不是计时器。
使用属性timeIntervalSince*
来记录最后一个脉冲的时间,并使用lastPulse
属性Bool
来跟踪正在进行的脉冲。仅在经过1秒且未激活脉冲时才运行函数。
pulseActive
注释:
- 您的
// time of last pulse // seed lastPulse with distantPast so first pulse will always succeed var lastPulse = Date.distantPast // are we in the middle of running a pulse? var pulseActive = false func pulseOn(on: Bool) { guard !pulseActive && abs(lastPulse.timeIntervalSinceNow) >= 1 else { return } pulseActive = true // record the time of this pulse lastPulse = Date() var pulseCount = 4 Timer.scheduledTimer(withTimeInterval: 0.025,repeats: true) { timer in print("PulseCount: \(pulseCount)") pulseCount = pulseCount - 1 if pulseCount < 1 { timer.invalidate() pulseActive = false // If you want the time from last pulse end to be 1 second // then set lastPulse here instead //lastPulse = Date() } } }
on:
未使用。我把它留在那里是因为我只想突出显示新代码。 - 尚不清楚您是希望1秒间隔是从脉冲开始到脉冲开始还是从脉冲结束到脉冲开始。如果您希望脉冲至少相隔1秒,则使用所编写的代码。如果您希望下一个脉冲在上一个脉冲结束后至少一秒钟开始,那么请在计时器无效时设置
Bool
。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。