Pausing a Program (Sleep)

Sometimes in a program you will want to pause, there are many different reasons why you might want to do this:

  • To not overload a user with information all at once,
  • As part of a timer program,
  • To make it seem as if a program is loading or thinking.

Whatever your reason, we use the sleep command to do so. Once you have imported sleep from the time library, you simply have to write the word sleep, followed by the number of seconds that you wish the program to pause for in brackets.

Below is an example of a program that imports the sleep command and waits for 3 seconds between printing:


And if we run this program you would see that the sleep command does not output anything to screen, it just waits when told to:


You can implement the sleep command within a for loop to produce an effective timer that outputs each second waited to the screen:

sleep3                                 sleep4

You could also use a variable instead of a fixed value with the sleep command such as below:


Practice Task 1

Sleeping not working? Tick off these common errors:

Have you imported sleep?
Have you stated how long to sleep for?

< Back to Section Five