Without stoping a timer, start again : will it cause running multiple timers in swift

Viewed 98

I have a function like below:

func startTimer() {
    let appDelegate = UIApplication.shared.delegate as! AppDelegate
    DispatchQueue.main.async {
        appDelegate.TIMER = Timer.scheduledTimer(withTimeInterval: self.REPEAT_TIME, repeats: true, block: { timer in                
            self.sendData(programID: self.MAIN_THREAD)
            do {
                try ...
            }
            catch let error {
                ...
            }
        })
    }
}

Timer Stop Function:

func stopTimer() {
    let appDelegate = UIApplication.shared.delegate as! AppDelegate
    if (appDelegate.TIMER != nil) {
        appDelegate.TIMER?.invalidate()
        appDelegate.TIMER = nil
    }
}

I want to know that

  1. is there any chance to start multiple timer instances if I call this function without stopping?

  2. And how about this case,(does this stopped only one timer & continue running another timer?)
    Start the timer → Start again → Stop

1 Answers

is there any chance to start multiple timer instances if I call this function without stopping?

Yes, startTimer will start another timer w/o stopping previous one, but as you store it in property TIMER you will loose reference to previously scheduled timer, so will be not able to stop it until end.

And how about this case,(does this stopped only one timer & continue running another timer?) Start the timer → Start again → Stop

Yes, it will stop last started timer and all other previously started timers will continue for self.REPEAT_TIME.

Related