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) ||
puts n
sleep()
puts
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) |
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.
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.
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:
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.
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.
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
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.
Difference Between require and include in Ruby
Learn the difference between require and include in Ruby, when to load a file, and when to mix module methods into a class.
Fixing Ruby Gem Native Extension Errors: mkmf.rb Can't Find Header Files for Ruby
Learn why Ruby gem installs fail with missing ruby.h, how native extensions work, and how to fix header file errors on Linux servers.