Delay A Function Call and Sleep A Thread in Swift

Function delays and thread sleep can be important tools for managing work in multi-threaded applications. This post presents examples for delaying a function call and sleeping threads in Swift:

  1. Delay A Function Call Using DispatchQueue
  2. Sleep A Thread For A Number Of Seconds
  3. Sleep A Thread Until A Specific Time

FREE all Swift loading animations.

Loading Animation Example

Follow AdvancedSwift and immediately get access to commented code for these animations that you can use in your projects.

Delay A Function Call Using DispatchQueue

DispatchQueue has different queues that you can execute code on, including main for the main thread and global() for background threads. A specific queue has an asyncAfter(deadline:, execute:) interface that will execute the code block execute after a specific deadline.

Here is an example of delaying a function call by 1 second without blocking the current thread:

// Call performTask after a delay of 1 second
DispatchQueue.main.asyncAfter(deadline: .now() + 1) {
    performTask()
}

Sleep A Thread For A Number Of Seconds

To block the current thread and sleep for a specific number of seconds, use Thread.sleep(forTimeInterval:)

// Sleep for 1 second
Thread.sleep(forTimeInterval: 1)

Sleep A Thread Until A Specific Time

Thread has another API for sleep, called Thread.sleep(until:). Use this API to sleep until a specific date:

// Sleep for 1 second
let deadline = Date().advanced(by: 1)
Thread.sleep(until: deadline)

Create A Delay and Make a Thread Wait in Swift

That’s it! By using Thread.sleep and DispatchQueue.asyncAfter you can implement delays and use sleep in your Swift code.