Question
How can you make a Ruby program wait for a chosen amount of time before continuing to the next line of code?
Short Answer
By the end of this page, you will understand how to pause execution in Ruby using sleep, how the delay is measured, what happens while the program is waiting, and how this is used in scripts, retries, polling, and rate-limited tasks.
Concept
In Ruby, the standard way to make a program wait is the sleep method.
sleep(2)
This pauses the current thread for about 2 seconds before the program continues.
Why this matters
Waiting is useful when your program needs to:
- pause between repeated actions
- retry after a failure
- avoid sending requests too quickly
- simulate time passing
- poll for a condition every few seconds
What sleep does
sleep temporarily stops execution of the current thread. After the specified duration passes, Ruby continues with the next line.
puts "Start"
sleep(1)
puts "End"
Output:
Start
End
There will be about a 1-second pause between the two lines.
Time units
The argument to sleep is measured in seconds.
sleep(5) # 5 seconds
sleep(0.5) # half a second
You can pass integers or floating-point numbers.
Important note
sleep is a blocking pause for the current thread. In a simple script, that usually means the whole program appears to stop temporarily. In multi-threaded Ruby code, other threads may still continue running.
Mental Model
Think of sleep like telling a worker: "Take a break for 2 seconds, then continue with the next task."
The code runs in order:
- do the current line
- pause for a set amount of time
- continue with the next line
Example:
puts "Boil water"
sleep(3)
puts "Add pasta"
It is like following a recipe that says: wait 3 minutes before the next step. The recipe does not skip ahead immediately; it pauses, then resumes.
Syntax and Examples
The basic syntax is:
sleep(seconds)
You can also call it without parentheses:
sleep 2
Example 1: Simple delay
puts "Loading..."
sleep(2)
puts "Done."
This waits about 2 seconds between the two messages.
Example 2: Fractional seconds
puts "Wait briefly"
sleep(0.25)
puts "Continue"
This pauses for a quarter of a second.
Example 3: Inside a loop
3.times do |i|
puts "Attempt #{i + 1}"
sleep(1)
end
This prints each attempt with a 1-second delay between iterations.
Example 4: Countdown
3.downto(1) do |n|
puts n
sleep(1)
end
puts "Go!"
This is a common beginner-friendly use of sleep.
Example 5: Using a variable
delay = 1.5
puts "Pausing for #{delay} seconds"
sleep(delay)
puts "Resumed"
This is helpful when the wait time comes from configuration or user input.
Step by Step Execution
Consider this code:
puts "Step 1"
sleep(2)
puts "Step 2"
Here is what happens step by step:
- Ruby executes
puts "Step 1"- The text
Step 1is printed.
- The text
- Ruby executes
sleep(2)- The current thread pauses for about 2 seconds.
- No next line runs during this pause.
- After about 2 seconds, Ruby continues.
- Ruby executes
puts "Step 2"- The text
Step 2is printed.
- The text
Trace with timing
Approximate timeline:
| Time | Action |
|---|---|
| 0.0s | Print Step 1 |
| 0.0s | Start sleep(2) |
| 2.0s | Finish sleeping |
| 2.0s | Print Step 2 |
Another traceable example
2.times do |i|
puts "Loop #{i}"
sleep(1)
end
puts "Finished"
Execution:
- First loop: print
Loop 0 - Wait 1 second
- Second loop: print
Loop 1 - Wait 1 second
- Print
Finished
Real World Use Cases
sleep appears in many practical Ruby programs.
1. Retrying a failed operation
begin
puts "Trying request..."
# request code here
rescue
puts "Failed, waiting before retry"
sleep(2)
retry
end
A short delay can prevent immediate repeated failures.
2. Polling for a status update
loop do
puts "Checking status..."
ready = [true, false].sample
break if ready
sleep(5)
end
puts "Status is ready"
This is common when checking whether a background job has finished.
3. Rate limiting API requests
items = [1, 2, 3]
items.each do |item|
puts "Sending request for #{item}"
sleep(1)
end
This can help avoid sending too many requests too quickly.
4. CLI animations or progress messages
puts "Starting"
sleep(1)
puts "Still working..."
sleep(1)
puts "Done"
Useful for command-line tools and demos.
5. Scheduled repeated tasks in simple scripts
loop do
puts "Running task at #{Time.now}"
sleep(10)
end
This is a basic pattern for repeated checks or maintenance jobs.
Real Codebase Usage
In real Ruby codebases, sleep is usually used carefully and for specific reasons.
Common patterns
Guarded retries
Developers often combine sleep with retries to avoid hammering a service.
attempts = 0
begin
attempts += 1
puts "Attempt #{attempts}"
raise "temporary error" if attempts < 3
puts "Success"
rescue => e
if attempts < 3
sleep(1)
retry
else
puts "Giving up: #{e.message}"
end
end
Polling loops with exit conditions
max_checks = 5
checks = 0
loop do
checks += 1
puts "Checking..."
break if checks == max_checks
sleep(2)
end
This avoids infinite busy-waiting.
Configuration-driven delays
RETRY_DELAY = 2
sleep(RETRY_DELAY)
Developers often store delays in constants or config files so they can be changed easily.
Test and demo code
Sometimes sleep is used in examples, scripts, or demos to make output easier to follow.
When teams are cautious
In production applications, developers avoid using sleep blindly because:
- it can slow programs unnecessarily
- it can block useful work
- it may hide timing problems instead of solving them
- event-driven or scheduled tools may be better for long waits
So sleep is common, but usually intentional and controlled.
Common Mistakes
Beginners often understand sleep quickly, but a few mistakes are common.
1. Thinking the value is milliseconds
In Ruby, sleep uses seconds, not milliseconds.
Broken expectation:
sleep(500)
A beginner may expect 500 milliseconds, but this waits 500 seconds.
Correct:
sleep(0.5)
2. Forgetting that sleep blocks the current thread
puts "Start"
sleep(10)
puts "This appears much later"
If your script seems frozen, it may just be sleeping.
3. Using sleep when waiting for a condition would be better
Broken pattern:
sleep(10)
puts "Assume file is ready"
This guesses instead of checking.
Better:
until File.exist?("done.txt")
sleep(1)
end
puts "File is ready"
4. Creating accidental infinite loops
loop do
puts "Running forever"
sleep(1)
end
This is valid, but if you forget a break condition, the program never stops.
5. Passing invalid values
Negative values are not useful and may raise errors depending on the Ruby version and environment.
Safer approach:
delay = 2
sleep(delay) if delay >= 0
6. Using long sleep calls in web request handling
In web apps, making a request wait with sleep can hurt performance.
Avoid patterns like this in request-response code unless you truly need them:
sleep(5)
render plain: "Done"
Comparisons
Here are some useful comparisons related to waiting in Ruby.
| Concept | What it does | Best used for |
|---|---|---|
sleep(2) | Pauses for about 2 seconds | Simple delays in scripts or loops |
| Busy waiting | Repeatedly checks without pausing | Usually avoid because it wastes CPU |
loop do ... sleep(1) end | Repeats work with pauses | Polling or periodic checks |
| Scheduling tools | Run tasks later or repeatedly | Cron jobs, background jobs, production scheduling |
sleep vs busy waiting
Busy waiting is inefficient:
until File.exist?("done.txt")
end
This keeps checking continuously and can waste CPU.
Better:
until File.exist?("done.txt")
sleep(1)
end
sleep vs timers or schedulers
- Use
sleepfor short, simple pauses in scripts. - Use schedulers, background jobs, or event systems for larger applications.
Integer seconds vs fractional seconds
| Example | Meaning |
|---|---|
sleep(1) | wait 1 second |
sleep(2.5) | wait 2.5 seconds |
sleep(0.1) | wait one-tenth of a second |
Cheat Sheet
Basic syntax
sleep(2)
sleep 2
sleep(0.5)
Key rules
sleeppauses execution of the current thread.- The argument is in seconds.
- Integers and floats are both valid.
- Code continues on the next line after the delay.
Common patterns
Pause between steps
puts "A"
sleep(1)
puts "B"
Delay inside a loop
loop do
puts "Checking..."
sleep(5)
end
Retry with delay
begin
# do work
rescue
sleep(1)
retry
end
Watch out for
sleep(500)means 500 seconds, not 500 milliseconds.- Long sleeps can make programs feel frozen.
- Infinite loops with
sleepstill run forever unless youbreak. - Use condition checks instead of guessing with fixed wait times when possible.
FAQ
How do I make Ruby wait for 1 second?
Use:
sleep(1)
Can Ruby sleep for less than a second?
Yes. Use a float:
sleep(0.25)
Is sleep measured in milliseconds or seconds?
It is measured in seconds.
Does sleep stop the whole Ruby program?
It pauses the current thread. In a simple script, that often feels like the whole program is paused.
Can I use sleep inside a loop?
Yes. This is common for polling or delaying repeated work.
Why does my program seem frozen?
It may be paused in a long sleep call.
Should I use sleep in a web application?
Usually only with care. In many web request paths, blocking waits can hurt performance.
What is the Ruby method for pausing execution?
The standard method is sleep.
Mini Project
Description
Build a small Ruby countdown script that pauses between numbers and then prints a final message. This project demonstrates how sleep controls timing in a real script and helps you see execution happen step by step.
Goal
Create a Ruby program that counts down once per second and then prints Liftoff!.
Requirements
- Print the numbers 3, 2, and 1 in order.
- Wait 1 second between each number.
- Print
Liftoff!after the countdown finishes.
Keep learning
Related questions
Add a Default Value to an Existing Column in a Rails Migration
Learn how to add or change a default value on an existing database column using Rails Active Record migrations safely.
Calling a Class Method from an Instance in Ruby
Learn how to call a class method from an instance in Ruby using self.class, with examples, pitfalls, and practical usage patterns.
Calling an Overridden Monkey-Patched Method in Ruby
Learn how to call the original method when monkey patching in Ruby, including alias_method patterns, examples, pitfalls, and practical usage.