0

I have one main ControllerView with two container view on top of each other (containerA on top of ContainerB). both containerView has a ControllerView. I am running a timer in each ContainerView. problem I am facing is that when I hide ContainerB to show ContainerA, the timer of containerB still running in the background, which is causing over 100% CPU use.

can any please help me how to stop the timer when I have other containerView visible? I am using two buttons to hide and show the container views.

ContainerA timer code:

ViewATimer = Timer.scheduledTimer(timeInterval: 1, target: self,   selector: (#selector(self.update)), userInfo: nil, repeats: true)

container B:

ViewBTimer = Timer.scheduledTimer(timeInterval: 10, target: self,   selector: (#selector(self.secondUpdate)), userInfo: nil, repeats: true)
Shehata Gamal
  • 98,760
  • 8
  • 65
  • 87

2 Answers2

0

When you show ContainerA do

ViewBTimer.invalidate()

ViewATimer = Timer.scheduledTimer(timeInterval: 1, target: self, selector: (#selector(self.update)), userInfo: nil, repeats: true)

//

When you show ContainerB do

ViewATimer.invalidate()

ViewBTimer = Timer.scheduledTimer(timeInterval: 10, target: self,   selector: (#selector(self.secondUpdate)), userInfo: nil, repeats: true)
Shehata Gamal
  • 98,760
  • 8
  • 65
  • 87
-1

To stop the timer

func stopTimer(timer: Timer) {
 if timer != nil {
    timer.invalidate()
    timer = nil
 }
}
Mehul Sojitra
  • 1,181
  • 9
  • 15