Sleep Function in GoLang

Learn via video courses
Topics Covered

Overview

The Sleep() function in Golang is used to stop the execution of the current go-routine for a specified amount of time. Once the sleep time is over the Go-routine will start its execution where it left off. In this article, we will learn more about Sleep in Golang.

Transform Your Career

Choose from our industry-leading programs designed for career success

NSDC Certified

Modern Software and AI Engineering Program

Master full-stack development with AI integration

12 MonthsDuration
AI-LedCurriculum
Career SupportSupport
GoogleAmazonPaytm+1000 more
Go to Program
NSDC Certified

Modern Data Science and ML with specialisation in AI

Advanced data science techniques with AI specialization

12 MonthsDuration
AI-LedCurriculum
Career SupportSupport
GoogleAmazonPaytm+1000 more
Go to Program
NSDC Certified

Advanced AIML with Specialisation in Agentic AI

Deep dive into AIML with focus on Agentic systems

12 MonthsDuration
AI-LedCurriculum
Career SupportSupport
GoogleAmazonPaytm+1000 more
Go to Program
NSDC Certified

DevOps, Cloud & AI Platform Engineering

Build and manage AI-powered cloud infrastructure

12 MonthsDuration
AI-LedCurriculum
Career SupportSupport
GoogleAmazonPaytm+1000 more
Go to Program
NSDC Certified

AI Engineering Advanced Certification by IIT-Roorkee

Premier AI engineering certification from IIT-Roorkee

3 MonthsDuration
AI-LedCurriculum
Career SupportSupport
Program highlights
Go to Program

Introduction

The Golang Sleep function is used to halt a process for a specified amount of time. It is available in the time package of standard libraries of Golang. The Syntax of the Sleep function is as Below;

The Sleep() Method

The sleep method takes the duration as an argument. This is the time for which the execution of the current go-routine will be stopped. If we pass negative or zero duration of sleep to the function it will cause this method to return instantly.

Let's assume we want to stop a process for 10 seconds. We can use the Sleep function as below.

Let's Implement an example for Golang Sleep().

Creating a Basic Timer Using the Sleep Function

Output:

Try on Playgroud.

Where is Sleep Useful in Go?

The Sleep Function is useful in the below situations.  

  • Threaded application where you want to pause a Go-routine.
  • Simulates timeouts.
  • Create Custom timers.

Func Sleep(d Duration)

We will create a random sleeping program and pass the variable Duration argument to Golang's Sleep() function.

Output:

Try on Playground.

Conclusion

  • Learned about Golang Sleep in-depth.
  • Implemented examples for Golang Sleep.
Hiring Partners:
GoogleGoogleAmazonAmazonMicrosoftMicrosoftFlipkartFlipkartAdobeAdobe1200+ more