In async code, call try await Task.sleep(for: .milliseconds(250)). It suspends the task without holding a thread, and it works at the top level of a script too. Outside async code, Thread.sleep(forTimeInterval: 0.25) blocks the thread. To run code later instead of waiting, the Swift 3+ form of dispatch_after is DispatchQueue.main.asyncAfter(deadline: .now() + .milliseconds(250)) { … }. To time something, use ContinuousClock().measure { … }.
Swift has two kinds of pause. A blocking sleep stops the thread it runs on, which is fine in a script and wrong on the main thread of an app, where it freezes the screen. A suspending sleep (Task.sleep) parks only the current task and lets the thread do other work meanwhile. And often you don't want to wait at all, just to run a closure later, which is what DispatchQueue.asyncAfter does. The sections below cover each one, the command-line catch with asyncAfter, cancelling a sleep and measuring elapsed time, then a table to pick from. The sleeps are kept short so the page stays quick. Each example runs on this page: hit Run, then edit the code and run it again.
1Task.sleep(for:)Recommended
Task.sleep(for:) takes a Duration, so the unit is part of the value: .milliseconds(250), .seconds(2) or .microseconds(500). It is async and throws (it throws when the task is cancelled, see section 6), so the call is try await. In a main.swift file you can write it at the top level, as here; elsewhere it must sit in an async function or a Task { … }. Duration and ContinuousClock are in the standard library, so this needs no import. The older Task.sleep(nanoseconds:) takes a UInt64 count of nanoseconds and does the same thing.
let clock = ContinuousClock() print("start") // Suspend this task for 250 ms; the thread is free for other work try await Task.sleep(for: .milliseconds(250)) print("after 250 ms") // The older form takes nanoseconds as a UInt64 try await Task.sleep(nanoseconds: 100_000_000) print("after another 100 ms") // A delay held in an Int: wrap it in the unit it is measured in let delayMs = 50 try await Task.sleep(for: .milliseconds(delayMs)) print("after \(delayMs) ms more") // Durations also come in seconds, microseconds and fractions let half: Duration = .seconds(0.5) print(half, Duration.milliseconds(1500), Duration.microseconds(250)) // Measure the sleep: a sleep is a minimum, never an exact time let start = clock.now try await Task.sleep(for: .milliseconds(150)) let elapsed = clock.now - start print("slept at least 150 ms:", elapsed >= .milliseconds(150))
Output
Each line appears after its pause. A Duration prints in seconds: 0.5 seconds 1.5 seconds 0.00025 seconds. The last line prints slept at least 150 ms: true rather than the raw time, because the exact figure changes from run to run: the task becomes ready once the time is up, and it resumes a little later. Task.sleep(for:) and Duration arrived in Swift 5.7 and need iOS 16 or macOS 13 on Apple platforms; for older deployment targets, use Task.sleep(nanoseconds:).
2Thread.sleep and usleep: blocking
In code that is not async, Foundation's Thread.sleep(forTimeInterval:) stops the current thread. Its argument is a TimeInterval, a Double counted in seconds, so 200 ms is 0.2. Thread.sleep(until:) takes a Date instead. The C function usleep takes microseconds, and sleep takes whole seconds; both come in with import Foundation. A blocking sleep is fine in a script or on a background thread. On the main thread of an app it freezes the interface for the whole pause, so use asyncAfter (section 3) there.
import Foundation let start = Date() // Foundation: TimeInterval is in seconds, so 0.2 means 200 ms Thread.sleep(forTimeInterval: 0.2) print("after 200 ms") // Sleep until a point in time Thread.sleep(until: Date().addingTimeInterval(0.1)) print("after another 100 ms") // POSIX usleep takes microseconds: 50_000 us = 50 ms usleep(50_000) print("after 50 ms more") let elapsed = Date().timeIntervalSince(start) print("blocked at least 350 ms:", elapsed >= 0.35) print("type of elapsed:", type(of: elapsed))
Output
The three pauses add up to blocked at least 350 ms: true, and timeIntervalSince returns a Double in seconds. Without import Foundation, usleep fails to compile with cannot find 'usleep' in scope. Don't mix the two kinds: once a file uses await at the top level, its top-level code is async, and Thread.sleep there warns class method 'sleep' is unavailable from asynchronous contexts; this is an error in the Swift 6 language mode. In async code, use Task.sleep.
3DispatchQueue.asyncAfter: the old dispatch_after
To run a closure after a delay without waiting for it, schedule it on a queue. The C call dispatch_after(dispatch_time(…), dispatch_get_main_queue(), …) from Swift 2 answers became DispatchQueue.main.asyncAfter(deadline:execute:) in Swift 3, and it has kept that form through Swift 5 and 6. The deadline is .now() plus a DispatchTimeInterval such as .milliseconds(300), or plus a Double in seconds. In an app the main queue is always running, so that one call is all you need. A command-line program is different: its main queue only runs if the program hands control to it with dispatchMain(), which never returns, so the closure ends the program with exit(0).
import Foundation print("scheduling") // The Swift 3+ form of dispatch_after: a deadline plus a closure DispatchQueue.main.asyncAfter(deadline: .now() + .milliseconds(300)) { print("300 ms later, on the main queue") exit(0) // dispatchMain() never returns, so end the program here } // Earlier deadlines run first, whatever the order you schedule them in DispatchQueue.main.asyncAfter(deadline: .now() + 0.1) { print("100 ms later (a Double counts as seconds)") } print("end of the top-level code") // A command-line program must run the main queue itself dispatchMain()
Output
asyncAfter returns at once, so end of the top-level code prints before either closure; then the 100 ms closure runs, then the 300 ms one. Delete the dispatchMain() line and the program prints only scheduling and end of the top-level code: it reaches the end of the file and exits with code 0 before any deadline, and the closures are silently dropped. That is the usual reason a delayed closure "never runs" in a script. The deadline is a minimum too: the closure runs once the queue gets to it.
4A background queue, waiting and cancelling
DispatchQueue.global().asyncAfter runs the closure on a background thread, so the main thread is free to wait for it. A DispatchGroup does the waiting: enter() before scheduling, leave() at the end of the closure, and wait() blocks until every enter has its leave. A DispatchSemaphore works the same way with signal() and wait(). To be able to call off a delayed block, wrap it in a DispatchWorkItem and call cancel() before its deadline.
import Foundation let group = DispatchGroup() // Run a closure after 200 ms on a background queue group.enter() DispatchQueue.global().asyncAfter(deadline: .now() + .milliseconds(200)) { print("200 ms later, on a background queue") group.leave() } // A DispatchWorkItem can be cancelled before its deadline let reminder = DispatchWorkItem { print("never printed: cancelled in time") } DispatchQueue.global().asyncAfter(deadline: .now() + .milliseconds(100), execute: reminder) reminder.cancel() print("scheduled, now waiting") // Block until every enter() has a matching leave() group.wait() print("done, isCancelled:", reminder.isCancelled)
Output
The main code prints scheduled, now waiting, blocks in group.wait() until the background closure has printed, then finishes with done, isCancelled: true. The cancelled work item never prints. Cancelling only stops a block that has not started yet; once it runs, cancel() does not interrupt it. If you wait on a semaphore instead of a group, semaphore.wait(timeout: .now() + .seconds(2)) returns .success when the closure signalled in time, and .timedOut if it did not.
5Measure elapsed time
ContinuousClock is the clock to time code with: it only moves forward. Its measure method runs a closure (an async one too) and returns the Duration it took, and subtracting two readings of clock.now gives a Duration as well. Divide a Duration by .milliseconds(1) to get a plain Double of milliseconds. Older code uses DispatchTime.now().uptimeNanoseconds, a UInt64, or Date, which follows the wall clock and can jump when the system time is set, so it is the wrong choice for timing.
import Foundation func work() -> Int { (1...200_000).reduce(0, &+) } // Clock.measure times a closure and returns a Duration let clock = ContinuousClock() let taken = clock.measure { _ = work() } print("measure returns a", type(of: taken)) print("under 5 s:", taken < .seconds(5)) // The closure can await, too let slept = try await clock.measure { try await Task.sleep(for: .milliseconds(120)) } print("slept at least 120 ms:", slept >= .milliseconds(120)) // Or read the clock twice and subtract let start = clock.now try await Task.sleep(for: .milliseconds(80)) let elapsed = clock.now - start print("at least 80 ms:", elapsed >= .milliseconds(80)) // Dividing by a Duration gives a plain Double let d: Duration = .milliseconds(1234) print(d, "=", d / .milliseconds(1), "ms") // DispatchTime counts nanoseconds since boot, as a UInt64 let t0 = DispatchTime.now() try await Task.sleep(for: .milliseconds(50)) let nanos = DispatchTime.now().uptimeNanoseconds - t0.uptimeNanoseconds print("at least 50 ms:", nanos >= 50_000_000) // Date works too, but it follows the wall clock, which can jump let began = Date() let seconds = Date().timeIntervalSince(began) print("Date gives seconds as a", type(of: seconds))
Output
The example prints comparisons instead of raw times, because those change on every run. In your own code, print(elapsed) shows the duration in the same form as 1.234 seconds, and d / .milliseconds(1) turns it into 1234.0 for logging. Time a debug build with care: this page compiles without optimizations, so loops run much slower here than in a release build. Swift also has SuspendingClock, which stops counting while the machine is asleep; the two differ only across such a pause.
6Delay work in a Task, and cancel it
The async version of "run this later" is a Task that sleeps first. Unlike asyncAfter, it can be cancelled even while it waits: task.cancel() wakes a sleeping Task.sleep at once, and the sleep throws CancellationError. Catch it to clean up, or write try? to let the sleep simply end early. await task.value waits for a task to finish.
let clock = ContinuousClock() let start = clock.now // Run code later without blocking: a Task that sleeps first let delayed = Task { try await Task.sleep(for: .milliseconds(200)) print("delayed work ran") } try await delayed.value // A long sleep in a task of its own let long = Task { do { try await Task.sleep(for: .seconds(10)) print("never printed") } catch { print("caught:", error) print("is CancellationError:", error is CancellationError) } } // Cancel it after 100 ms: the sleep throws right away try await Task.sleep(for: .milliseconds(100)) long.cancel() await long.value let elapsed = clock.now - start print("well under 10 s:", elapsed < .seconds(2)) // try? ignores the error: the sleep just ends early let quiet = Task { try? await Task.sleep(for: .seconds(10)) print("woke early, cancelled:", Task.isCancelled) } quiet.cancel() await quiet.value
Output
The 10-second sleep ends after about 100 ms with caught: CancellationError(), and the whole run prints well under 10 s: true. With try? the error is thrown away and the code after the sleep runs anyway, so check Task.isCancelled (here true) before doing the delayed work. A blocking Thread.sleep cannot be cut short like this: it always runs to the end.
7Which should you use?
| Method | Blocks the thread | Best for |
|---|---|---|
| try await Task.sleep(for: .milliseconds(n)) | No, suspends | Any async code; pauses you can cancel |
| Thread.sleep(forTimeInterval: s) | Yes | Scripts and background threads, outside async code |
| usleep(us) / sleep(s) | Yes | Ports of C code; prefer Thread.sleep |
| DispatchQueue.main.asyncAfter | No, schedules | Running a closure later in an app (dispatch_after) |
| DispatchWorkItem + asyncAfter | No, schedules | A delayed block you may call off before it starts |
| ContinuousClock().measure { } | Timing, not a pause | Measuring elapsed time |
Frequently asked questions
Why does my asyncAfter closure never run?
In a command-line program, the top-level code finishes, the program exits, and pending closures are dropped. A program that schedules on DispatchQueue.main and then reaches the end of the file prints its own lines and nothing from the closure. Call dispatchMain() at the end and exit(0) from the last closure, wait with a DispatchGroup or semaphore on a global queue, or use try await Task.sleep. In an app the main queue is already running, so the closure fires.
Should I use Thread.sleep or Task.sleep?
In async code, always Task.sleep: it frees the thread while it waits and can be cancelled. Thread.sleep blocks the thread, and in an async context it warns class method 'sleep' is unavailable from asynchronous contexts; this is an error in the Swift 6 language mode. Use Thread.sleep(forTimeInterval:) only in plain synchronous code such as a script or a background thread, never on the main thread of an app.
How do I sleep with sleep() or usleep() in Swift?
Both are C functions that come in with import Foundation. sleep(2) pauses for whole seconds and usleep(250_000) for microseconds, here 250 ms. Without the import the compiler says cannot find 'usleep' in scope. They block the thread like Thread.sleep, and Thread.sleep(forTimeInterval: 0.25) says the same thing more clearly.
Is a Swift sleep exact?
No. Every sleep and every asyncAfter deadline is a minimum: the code becomes ready to run when the time is up, and it resumes shortly after. That is why the examples print elapsed >= .milliseconds(150) rather than the raw time. Never use a sleep to wait for other work to finish; use await, a DispatchGroup or a semaphore.
How do I repeat something every few milliseconds?
In async code, loop and sleep: while !Task.isCancelled { doWork(); try await Task.sleep(for: .milliseconds(100)) }. Timer.scheduledTimer(withTimeInterval:repeats:) needs a running run loop: in a script with no run loop, a 100 ms timer fired 0 times in 350 ms here, while RunLoop.current.run(until:) made it tick. In an app the main run loop is already running.
How do I get milliseconds out of a Duration?
Divide by a one-millisecond Duration: Duration.milliseconds(1234) / .milliseconds(1) is the Double 1234.0. Printing a Duration shows seconds, such as 1.234 seconds. For the raw parts, components returns the whole seconds and the remaining attoseconds.