Reputation: 5
how does a timer in timer worked?
func startSequenz()
{
for mainCell in mainTable {
timer = Timer.scheduledTimer(timeInterval: 1, target: self, selector:#selector(ViewController.run), userInfo: nil, repeats: true)
}
}
func run ()
{
for cell in table{
timer2 = Timer.scheduledTimer(timeInterval: 1, target: self, selector:#selector(ViewController.run2), userInfo: nil, repeats: true)
}
timer!.invalidate()
}
func run2()
{
currentSteps! += 1
print("\(currentSteps!)")
timer2!.invalidate()
}
Executing func run2()
never stops. My target is, to delay the execute of run2 and sleep(1)
freez the GUI.
UPDATE:
I´ve use Tom E answer and it worked partially. But the GUI refresh only once at the end of the execute.
func run ()
{
for cell in table{
DispatchQueue.global().asyncAfter(deadline: .now() + .seconds(2)) {
// This code will be placed on a background queue and be executed a second later
// i do my stuff
DispatchQueue.main.async {
// Here you may update any GUI elements
self.currentCell = cell
self.currentStep! += 1
self.sectionHeaderText = "\(self.currentStep!) of \(self.totalSteps!)"
self.tableView.reloadSections(IndexSet(integer: 0), with: .none)
}
}
}
}
public override func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
switch section {
case 0 : return sectionHeaderText
default : return nil
}
}
Upvotes: 0
Views: 425
Reputation: 1607
It doesn’t seem to make much sense to create a repeating timer which will immediately be invalidated upon the first time its action method is called.
If you seek for proper ways to delay the execution of code please have a look at Grand Central Dispatch. Here’s a sample of code with non-blocking, delayed background execution:
DispatchQueue.global().asyncAfter(deadline: .now() + .seconds(1)) {
// This code will be placed on a background queue and be executed a second later
DispatchQueue.main.async {
// Here you may update any GUI elements
}
}
Please make sure you don’t access any GUI elements from a background queue. For this reason the sample shows how to switch to the main thread for any GUI updates.
Upvotes: 1