Ad space (banner)
๐ŸฆSwift Lessons
Lesson 56 / 68

Waiting for a Fixed Amount of Time (Thread.sleep)

In this lesson you will learn how to pause for a set time with Thread.sleep in Swift, covering the basics of programs that deal with time. This is for anyone searching for "Swift Thread.sleep how to use".

Thread.sleep(forTimeInterval:) pauses processing for the number of seconds you specify. Use it to space out calls to an API, or to slow a process down deliberately.

The sample code prints "Starting", waits one second with Thread.sleep(forTimeInterval: 1.0), and then prints "Ran after 1 second". Notice that the duration can be a decimal.

A common stumbling block for beginners is over-using Sleep and making the whole program feel unresponsive. It is the foundation of programs that deal with the passage of time, such as GUI apps and game frame timing, but take care not to block the main screen.

In real-world development it is also used for waiting a moment before retrying, to avoid hammering a server with requests.

๐Ÿ“– Reference code
โœ๏ธ Your code
Type your code, then press "Run"

๐Ÿงช This site can't compile or run Swift directly, so it checks on the spot whether what you typed matches the reference code (scoring happens entirely in your browser โ€” nothing is sent anywhere).

Ad space (banner)
Ad space (in-article)