Ad space (banner)
๐Ÿ’ŽRuby Lessons
Lesson 56 / 68

Waiting for a Fixed Amount of Time (sleep)

In this lesson you will learn to pause for a set time with sleep so you can write programs that control their own timing. This is for anyone searching for "Ruby sleep how to use".

sleep(seconds) 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 sleep(1), and then prints "Ran after 1 second". Change the number and watch the wait change with it.

A common stumbling block for beginners is that sleep() stops the process completely. If you want work to continue in parallel you need Thread or a more advanced asynchronous mechanism; for a simple pause, sleep is enough.

It is also used in practice for waiting a moment before retrying, to avoid hammering a server with requests. It is the foundation of programs that deal with the passage of time, such as GUI applications and game frame timing.

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

๐Ÿงช This site can't compile or run Ruby 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)