Swift
programming
delay
tutorial
iOS development

How to create a delay in Swift?

Interview Questions practice on Codemia

Over 8,000 real interview questions from top companies, searchable by company and role.

Browse interview questions

Creating delays in Swift can be a useful strategy in various scenarios, such as scheduling network requests, waiting for resources to become available, or simply improving the user experience by pacing animations or transitioning between UI elements. Swift offers a range of approaches to implement delays, whereby developers can choose the most suitable method according to their specific use case. This article dives into several techniques to create delays in the Swift programming language, elucidating their technical working, accompanied by examples and a summarizing table.

Key Techniques for Creating Delays in Swift

1. Using DispatchQueue

The Grand Central Dispatch (GCD) framework provides powerful tools for managing concurrent execution. A common strategy for creating delays is by using DispatchQueue.

swift
DispatchQueue.main.asyncAfter(deadline: .now() + 2.0) {
    print("Delayed by 2 seconds")
}

Explanation:

  • DispatchQueue.main targets the main thread. Alternatively, you could use another queue if preferred.
  • asyncAfter(deadline:) schedules a block of code to be executed after a certain amount of time.
  • .now() + 2.0 calculates the deadline using the current time plus the delay interval in seconds.

2. Using Thread.sleep

Although not highly recommended due to potential side-effects like blocking the current thread, Thread.sleep(forTimeInterval:) can be useful in simpler or non-concurrent scenarios.

swift
print("Start")
Thread.sleep(forTimeInterval: 2.0)
print("Delayed by 2 seconds")

Explanation:

  • Stops the current thread execution for a specified number of seconds.
  • Should be used cautiously in UI applications to avoid freezing the interface.

3. Using Timer for Repeated Delays

For repeated delays, the Timer class can be especially beneficial. It gives precise control over interval-based events.

swift
Timer.scheduledTimer(withTimeInterval: 2.0, repeats: false) { timer in
    print("Delayed by 2 seconds")
}

Explanation:

  • Creates a scheduled timer that fires after 2.0 seconds.
  • Set repeats to true for recurring actions.

4. Using RunLoop

The RunLoop approach can also be leveraged for delaying code execution while keeping the application responsive.

swift
let twoSecondsFromNow = Date().addingTimeInterval(2.0)
RunLoop.current.run(until: twoSecondsFromNow)
print("Delayed by approximately 2 seconds")

Explanation:

  • Date().addingTimeInterval(2.0) computes a target date by adding a delay.
  • RunLoop.current.run(until:) runs until the future date is reached, offering a rough delay mechanism.

Key Points & Summary

Below is a concise table summarizing the essential points of each method:

MethodExecution ContextBlocking NatureRecommended Use Cases
DispatchQueueAsynchronousNon-blockingUI tasks, animations, network requests.
Thread.sleepAny threadBlocking the current threadSimple tasks, avoid in UI-heavy applications.
TimerAsynchronousNon-blockingRepeated tasks and interval-based scheduling.
RunLoopMain or backgroundNon-blocking but halts executionSimple delay without blocking UI interactions.

Additional Considerations

Precision and Reliability

  • Timers may not be completely accurate, particularly when the system load is high. Use a background queue for more crucial timing tasks.
  • DispatchQueue is generally more performant and reliable compared to inline or block-thread techniques.

Impact on User Experience

  • Avoid direct blocking methods like Thread.sleep in main threads of UI applications, as this can freeze the interface and degrade user interaction.

Leveraging Async/Await

For methods running in Swift 5.5 and above, the use of async/await can structure asynchronous tasks around delays more naturally and readably.

swift
1func delayedPrint() async {
2    try? await Task.sleep(nanoseconds: 2_000_000_000) // 2 seconds
3    print("Delayed by 2 seconds using async/await")
4}

Note: The Task.sleep(nanoseconds:) method provides a granularity that previous methods do not, being capable of understanding time at the nanosecond level.

By considering the particular requirements and constraints of your application, you can choose the most effective method to introduce delays in your Swift code efficiently and effectively. Integrating these techniques thoughtfully will enhance functionality and promote a smoother user experience.


Related reading
Free course
Beginner
7 lessons
2 hours
Tackling System Design Interview Problems

A short course that equips you with the skills to approach system design interviews methodically.

Start the free course
Track what you have practised

A free account saves your progress, solutions and study plan across every problem on Codemia.

Interview Questions practice on Codemia

Over 8,000 real interview questions from top companies, searchable by company and role.

Browse interview questions

All Rights Reserved.