Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • JS Tutorial
  • JS Exercise
  • JS Interview Questions
  • JS Array
  • JS String
  • JS Object
  • JS Operator
  • JS Date
  • JS Error
  • JS Projects
  • JS Set
  • JS Map
  • JS RegExp
  • JS Math
  • JS Number
  • JS Boolean
  • JS Examples
  • JS Free JS Course
  • JS A to Z Guide
  • JS Formatter
Open In App
Next Article:
JavaScript Atomics wait() Method
Next article icon

How to Make JavaScript Sleep or Wait?

Last Updated : 27 Nov, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

In JavaScript, there is no built-in sleep function like in some other programming languages. However, you can create a delay or pause in code execution by using asynchronous methods.

We can use setTimeout() or Promise along with async/await to achieve this functionality for more readable code.

1. Using setTimeout() and Promises

The setTimeout() function is used to schedule a function to run after a specified delay. By combining it with Promises, we can create a custom sleep() function that pauses code execution for a defined time.

JavaScript
async function main() {   console.log("Before sleep");   await sleep(2000); // Sleep for 2 seconds   console.log("After sleep [After 2 Seconds]"); }  function sleep(time) {   return new Promise((resolve) => setTimeout(resolve, time)); }  main(); 

Output

Output
How to Make JavaScript Sleep or Wait

2. Using async/await Keyword

You can simplify the code and improve readability by using async/await with the sleep function. The await keyword pauses the execution of the function until the Promise returned by the sleep function is resolved.

JavaScript
async function main() {   console.log("Before sleep");   await sleep(5000); // Sleep for 5 seconds   console.log("After sleep [After 5 Seconds]"); }  async function sleep(ms) {   await new Promise((resolve) => setTimeout(resolve, ms)); }  main(); 

Output

Output
How to Make JavaScript Sleep or Wait

Both approaches provide ways to pause code execution for a specified duration, allowing us to control the flow of our JavaScript programs. Whether you choose the setTimeout() and Promises approach or the async/await approach depends on your preference and the requirements of your project.


Next Article
JavaScript Atomics wait() Method

G

gpancomputer
Improve
Article Tags :
  • JavaScript
  • Web Technologies
  • JavaScript-Methods
  • JavaScript-Questions

Similar Reads

  • How to Wait n Seconds in JavaScript?
    Here are the various methods to wait n seconds in JavaScript 1. Using setTimeout() FunctionsetTimeout() is an asynchronous function in JavaScript that allows you to run code after a specific amount of time has passed. Since setTimeout() is a method of the window object, you can technically write it
    3 min read
  • How to wait for multiple Promises in JavaScript ?
    Waiting for multiple promises in JavaScript involves using Promise.all() or Promise.allSettled() methods. These methods accept an array of promises as input. Promise.all() waits for all promises to either resolve or reject, providing a single promise that resolves with an array of results or rejects
    3 min read
  • How to Detect Network Speed using JavaScript?
    Network speed detection in JavaScript involves measuring the time it takes to download a known file or resource and calculating the download speed. To calculate the speed of the network a file of known size is chosen from a server to download. The time taken to start and complete the download is rec
    2 min read
  • JavaScript Atomics wait() Method
    The Atomics.wait() in JavaScript is an in-built method that is used to verify whether a given position in an Int32Array still contains a given value and if so sleeps, awaiting a wakeup or a timeout. The Atomics.wait() operation returns a string that is either "ok", "not-equal", or "timed-out". The i
    2 min read
  • How to set the cursor to wait in JavaScript ?
    In JavaScript, we could easily set the cursor to wait. In this article, we will see how we are going to do this. Actually, it's quite an easy task, there is a CSS cursor property and it has some values and one of the values is wait. We will use the [cursor: wait] property of CSS and control its beha
    3 min read
  • How JavaScript Works?
    JavaScript is a dynamically typed, cross-platform threaded scripting and programming language, used to put functionality and interactivity at the client side as well as to write logic on the server side of a website. It can display content updates, interactive maps, control multimedia, interactive f
    14 min read
  • JavaScript setTimeout() Method
    JavaScript setTimeout() method allows you to schedule the execution of a function or the evaluation of a code after a specified delay. The setTimeout() method calls a function after several milliseconds. setTimeout() is for executing a function once after a specified delay. Syntax:setTimeout(functio
    2 min read
  • JavaScript setInterval() Method
    The setInterval() method calls a function at specified intervals (in milliseconds). It continues calling the function until clearInterval() is called or the window is closed. This method is useful for tasks that need periodic execution, like updating animations or refreshing data. Important Note: se
    2 min read
  • JavaScript Atomics waitAsync() Method
    Among the Atomic operations the Atomics.waitAsync() operator is used to make an operation wait asynchronously on memory and returns a promise. It is non-blocking as compared to Atomics.wait() and can be used on the main thread. If the promise is not fulfilled then it will lead to a 'time-out' status
    2 min read
  • How to change cursor to waiting state in JavaScript/jQuery ?
    Given an HTML document and the task is to get the waiting state cursor when the mouse moves over an element. Here we are going to achieve that by cursor property which allows doing an operation on the cursor. We are going to do that with the help of JavaScript.Approach:   Use the cursor property.Set
    3 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences