【问题标题】:Swift Timer that will not run again until a certain period of timeSwift Timer 直到某个时间段才会再次运行
【发布时间】:2020-09-28 07:18:49
【问题描述】:

这被证明是一个挑战,我想要一个计时器,它可以触发 10 秒的脉冲,然后有效地阻止它再次运行,直到至少 1 秒过去。

这是 pulse 的代码,但我怎样才能阻止它再次触发,直到 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()
   
        }
    }
}

【问题讨论】:

  • 0.025 * 4 = 0.1,而不是 1 秒。也许这就是问题
  • 我认为您可以在此计时器内触发另一个函数,该函数将 bool 设置为 false 并运行一个计时器一秒钟,将 bool 更改为 true。然后只在 bool 为真时运行你的原始计时器?
  • 我推荐使用DispatchSourceTimer。它更灵活、更准确,可以暂停和恢复。

标签: swift timer nstimer


【解决方案1】:

当测量两个事件之间的时间时,使用Date 及其timeIntervalSince* 函数而不是计时器。

使用属性lastPulse 记录最后一次脉冲的时间,并使用Bool 属性pulseActive 来跟踪是否正在进行脉冲。仅在 1 秒过去且脉冲未激活时才运行您的函数。

// 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: Bool 未使用。我把它留在那里是因为我只想突出显示新代码。
  • 不清楚您是否希望 1 秒间隔是从脉冲开始到脉冲开始或脉冲结束到脉冲开始。如果您希望脉冲开始至少相隔 1 秒,则使用编写的代码。如果您希望在上一个脉冲结束后至少一秒开始下一个脉冲,则在计时器无效时设置lastPulse = Date()

【讨论】:

  • 非常感谢,就是这样做的。
  • 请为您认为有帮助的答案投票,并通过选中答案左侧的灰色复选标记将其变为绿色来接受最有帮助的答案。
【解决方案2】:

可能是这样的。添加一个布尔值;

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()
}

【讨论】:

  • 谢谢,明天会破解的:)
猜你喜欢
  • 1970-01-01
  • 2021-04-16
  • 1970-01-01
  • 2021-05-29
  • 2018-01-07
  • 2017-10-31
  • 1970-01-01
  • 1970-01-01
  • 2020-05-14
相关资源
最近更新 更多