How to add a 5 second delay to a function

I have a function that changes the Table type (background) at points in a game. The change happens ok but I am trying to add a 5 second delay before the switch from the current table type to the new table type but I cannot get the delay to work.

The code for the replace table function is below. Any help would be great.

func replaceTable() {
        //add delay between table change

        let secondsToDelay = 5.0
        DispatchQueue.main.asyncAfter(deadline: .now() + secondsToDelay) {

            // remove existing table before adding new one

            if let table = self.currentTable {
  table.removeFromParent()
  self.currentTable = nil
    }  }

         let table = SKSpriteNode(imageNamed: tableType.imageName)
  addChild(table)
  table.position = CGPoint(x: size.width/2, y: size.height/2)
  table.zPosition = -1   switch tableType {

        case .bond:

                //...

                break

            case .ovaloffice:

                //...

                break

            case .austin:

                //...

                break

            case .deadpool:

                //...

                break

            case .moesbar:

                //...

                break

            case .casino:

                //...

                break
        }

    }
Your text formatting is terrible.
Please use formatter (<>) to improve, and paste code with Paste and Match Style:

Code Block
func replaceTable() {
//add delay between table change
let secondsToDelay = 5.0
DispatchQueue.main.asyncAfter(deadline: .now() + secondsToDelay) {
// remove existing table before adding new one
if let table = self.currentTable {
table.removeFromParent()
self.currentTable = nil
}
}
let table = SKSpriteNode(imageNamed: tableType.imageName)
addChild(table)
table.position = CGPoint(x: size.width/2, y: size.height/2)
table.zPosition = -1
switch tableType {


What happens:
  • line 5, you dispatch

  • then execution continues immediately at line 13

  • and line 7 will be executed after 5 seconds.

To see this, instrument code as follows:
Code Block
func replaceTable() {
//add delay between table change
let secondsToDelay = 5.0
print("Before")
DispatchQueue.main.asyncAfter(deadline: .now() + secondsToDelay) {
// remove existing table before adding new one
print("Delayed")
if let table = self.currentTable {
table.removeFromParent()
self.currentTable = nil
}
}
print("After")
let table = SKSpriteNode(imageNamed: tableType.imageName)
addChild(table)
table.position = CGPoint(x: size.width/2, y: size.height/2)
table.zPosition = -1
switch tableType {


You will get on Console:
Before
After

And 5 seconds later
Delayed

So you need to move lines 13 and onward inside the dispatch, at the end.
How to add a 5 second delay to a function
 
 
Q