Technology3 min read

The 'time.sleep' Function in Python

Abhishek Ahlawat

By Abhishek Ahlawat โ€” Recently

Founder of StudyTonight and a MERN fullstack developer. Writes about JavaScript, web development, Linux, and tech.

#Python#Python Time

Summarize this article using AI

Sometimes, it may be required to give a timeout or stop the processing for a certain amount of time. This is when the sleep functionality comes into play. The sleep function is present in the time module in Python. It is an accurate method to halt the flow of control in python code.


Syntax of the sleep function

Following is the syntax of the function,

time.sleep(second)

The second parameter tells the amount of time for which the code has to halt the execution. It doesn't return anything.

Let's take a code example,

import time 

print("The code begins execution at: ", end ="") 
print(time.ctime())

time.sleep(12) 

print("The code execution ends at: ", end ="") 
print(time.ctime()) 

Output:

The code begins execution at: Tue Dec 31 11:32:58 2019
The code execution ends at: Tue Dec 31 11:33:10 2019



Applications of the sleep function

Following are some of the applications of the following function:

  1. Running background processes at specific intervals of time.

  2. Providing a better user interface by giving some time gap between typing letters.

The above application can be seen in action with the below code example:

Note: Make sure to run it on your IDE to see how it works.

import time 

my_str = "Studytonight" 

for i in range(0, len(my_str)): 
    print(my_str[i], end ="") 
    time.sleep(1) 

Output:

Studytonight



Conclusion:

In this post, we understood how the sleep function of the time module in python works. Let us know your thoughts on this function's usage in the comment section below.

Spotted something outdated or wrong?

Liked this? See more StudyTonight posts in Google results.

Add StudyTonight as a preferred source
Next questLIVE OPSStep 2 / 3

Practice real incidents in the browser

System Design Ops โ€” put out fires, ship fixes, and stack XP. Reading done. Time to play.

Play System Design
  • +XP

    Every sim

  • Incidents

    Live ops

  • Ranks

    Climb up

Read next