search
HomeWeb Front-endJS TutorialImplementing sleep or wait using JavaScript

Implementing sleep or wait using JavaScript

JavaScript does not have a sleep() function, which causes the code to wait for a specified period of time before resuming execution. What should I do if I need JavaScript to wait?

Suppose you want to log three messages to the Javascript console, with a one second delay between each message. There is no sleep() method in JavaScript, so you can try to use the next best method setTimeout().

Unfortunately, setTimeout() doesn't work as well as you might expect, depending on how you use it. You've probably tried this at some point in your JavaScript loop and seen that setTimeout() doesn't seem to work at all.

The problem arises from misunderstanding setTimeout() as the sleep() function, when in fact it works according to its own set of rules.

In this article, I will explain how to use setTimeout(), including how to use it to make a sleep function that causes JavaScript to pause execution and wait between consecutive lines of code.

Looking through the documentation for setTimeout(), it seems to require a "delay" parameter, in milliseconds.

Back to the original question, you are trying to call setTimeout(1000) to wait 1 second between calls to the console.log() function.

Unfortunately setTimeout() doesn't work like this:

setTimeout(1000)
console.log(1)
setTimeout(1000)
console.log(2)
setTimeout(1000)
console.log(3)

for (let i = 0; i <= 3; i++) {
  setTimeout(1000)
  console.log(`#${i}`)
}

The result of this code is completely undelayed, like setTimeout() does Existence is the same.

Looking back at the documentation, you'll find that the problem is that the first parameter should actually be a function call, not a delay. After all, setTimeout() is not actually a sleep() method.

You rewrite the code to take the callback function as the first parameter and the required delay as the second parameter:

setTimeout(() => console.log(1), 1000)
setTimeout(() => console.log(2), 1000)
setTimeout(() => console.log(3), 1000)

for (let i = 0; i <= 3; i++) {
  setTimeout(() => console.log(`#${i}`), 1000)
}

In this way, the three console.log log messages are in After a single delay of 1000ms (1 second), they are displayed together, rather than the ideal effect of a 1 second delay between each repeated call.

Before discussing how to solve this problem, let's examine the setTimeout() function in more detail.

Check setTimeout()

You may have noticed the use of arrow functions in the second code snippet above. These are required because you need to pass an anonymous callback function to setTimeout(), which will run the code to be executed after the timeout.

In an anonymous function, you can specify arbitrary code to be executed after the timeout:

// 使用箭头语法的匿名回调函数。
setTimeout(() => console.log("你好!"), 1000)
// 这等同于使用function关键字
setTimeout(function() { console.log("你好!") }, 1000)

Theoretically, you can just pass the function as the first parameter, and the parameters of the callback function as the remainder parameters, but this never seemed to work correctly for me:

// 应该能用,但不能用
setTimeout(console.log, 1000, "你好")

People solved this problem using strings, but this is not recommended. Executing JavaScript from a string has security implications, as any bad actor can run arbitrary code injected as a string.

// 应该没用,但确实有用
setTimeout(`console.log("你好")`, 1000)

So why does setTimeout() fail in our first set of code examples? It seems like we are using it correctly, the 1000ms delay is repeated every time.

The reason is that setTimeout() is executed as synchronous code, and multiple calls to setTimeout() all run simultaneously. Each call to setTimeout() creates asynchronous code that will be executed later after a given delay. Since every delay in the snippet is the same (1000 ms), all queued code will run simultaneously after a single delay of 1 second.

As mentioned before, setTimeout() is not actually a sleep() function, instead it just queues asynchronous code for later execution . Fortunately, it's possible to create your own sleep() function in JavaScript using setTimeout().

How to write a sleep function

With the functions of Promises, async and await, you can write a sleep() function, which will behave as expected.

However, you can only call this custom sleep() function from an async function, and you need to combine it with the await keyword use together.

This code demonstrates how to write a sleep() function:

const sleep = (delay) => new Promise((resolve) => setTimeout(resolve, delay))

const repeatedGreetings = async () => {
  await sleep(1000)
  console.log(1)
  await sleep(1000)
  console.log(2)
  await sleep(1000)
  console.log(3)
}
repeatedGreetings()

This JavaScript sleep() function does what you would expect Exactly the same, because await causes the synchronous execution of the code to be paused until the Promise is resolved.

A simple option

Alternatively, you can specify an increased timeout when first calling setTimeout().

The following code is equivalent to the previous example:

setTimeout(() => console.log(1), 1000)
setTimeout(() => console.log(2), 2000)
setTimeout(() => console.log(3), 3000)

Using increased timeout is feasible, because the code is executed at the same time, so the specified callback function will be executed at 1 and 2 of the synchronous code and execute after 3 seconds.

Will it run in a loop?

As you might expect, both of the above options for pausing JavaScript execution work fine within a loop. Let's look at two simple examples.

This is a code snippet using a custom sleep() function:

const sleep = (delay) => new Promise((resolve) => setTimeout(resolve, delay))

async function repeatGreetingsLoop() {
  for (let i = 0; i <= 5; i++) {
      await sleep(1000)
    console.log(`Hello #${i}`)
    }
}
repeatGreetingsLoop()

这是一个简单的使用增加超时的代码片段:

for (let i = 0; i <= 5; i++) {
  setTimeout(() => console.log(`Hello #${i}`), 1000 * i)
}

我更喜欢后一种语法,特别是在循环中使用。

总结

JavaScript可能没有 sleep()wait() 函数,但是使用内置的 setTimeout() 函数很容易创建一个JavaScript,只要你谨慎使用它即可。

就其本身而言,setTimeout() 不能用作 sleep() 函数,但是你可以使用 asyncawait 创建自定义JavaScript sleep() 函数。

采用不同的方法,可以将交错的(增加的)超时传递给 setTimeout() 来模拟 sleep() 函数。之所以可行,是因为所有对setTimeout() 的调用都是同步执行的,就像JavaScript通常一样。

希望这可以帮助你在代码中引入一些延迟——仅使用原始JavaScript,而无需外部库或框架。

祝您编码愉快! 

英文原文地址:https://medium.com/dev-genius/how-to-make-javascript-sleep-or-wait-d95d33c99909

作者:Dr. Derek Austin

更多编程相关知识,请访问:编程视频!!

The above is the detailed content of Implementing sleep or wait using JavaScript. For more information, please follow other related articles on the PHP Chinese website!

Statement
This article is reproduced at:segmentfault. If there is any infringement, please contact admin@php.cn delete
From Websites to Apps: The Diverse Applications of JavaScriptFrom Websites to Apps: The Diverse Applications of JavaScriptApr 22, 2025 am 12:02 AM

JavaScript is widely used in websites, mobile applications, desktop applications and server-side programming. 1) In website development, JavaScript operates DOM together with HTML and CSS to achieve dynamic effects and supports frameworks such as jQuery and React. 2) Through ReactNative and Ionic, JavaScript is used to develop cross-platform mobile applications. 3) The Electron framework enables JavaScript to build desktop applications. 4) Node.js allows JavaScript to run on the server side and supports high concurrent requests.

Python vs. JavaScript: Use Cases and Applications ComparedPython vs. JavaScript: Use Cases and Applications ComparedApr 21, 2025 am 12:01 AM

Python is more suitable for data science and automation, while JavaScript is more suitable for front-end and full-stack development. 1. Python performs well in data science and machine learning, using libraries such as NumPy and Pandas for data processing and modeling. 2. Python is concise and efficient in automation and scripting. 3. JavaScript is indispensable in front-end development and is used to build dynamic web pages and single-page applications. 4. JavaScript plays a role in back-end development through Node.js and supports full-stack development.

The Role of C/C   in JavaScript Interpreters and CompilersThe Role of C/C in JavaScript Interpreters and CompilersApr 20, 2025 am 12:01 AM

C and C play a vital role in the JavaScript engine, mainly used to implement interpreters and JIT compilers. 1) C is used to parse JavaScript source code and generate an abstract syntax tree. 2) C is responsible for generating and executing bytecode. 3) C implements the JIT compiler, optimizes and compiles hot-spot code at runtime, and significantly improves the execution efficiency of JavaScript.

JavaScript in Action: Real-World Examples and ProjectsJavaScript in Action: Real-World Examples and ProjectsApr 19, 2025 am 12:13 AM

JavaScript's application in the real world includes front-end and back-end development. 1) Display front-end applications by building a TODO list application, involving DOM operations and event processing. 2) Build RESTfulAPI through Node.js and Express to demonstrate back-end applications.

JavaScript and the Web: Core Functionality and Use CasesJavaScript and the Web: Core Functionality and Use CasesApr 18, 2025 am 12:19 AM

The main uses of JavaScript in web development include client interaction, form verification and asynchronous communication. 1) Dynamic content update and user interaction through DOM operations; 2) Client verification is carried out before the user submits data to improve the user experience; 3) Refreshless communication with the server is achieved through AJAX technology.

Understanding the JavaScript Engine: Implementation DetailsUnderstanding the JavaScript Engine: Implementation DetailsApr 17, 2025 am 12:05 AM

Understanding how JavaScript engine works internally is important to developers because it helps write more efficient code and understand performance bottlenecks and optimization strategies. 1) The engine's workflow includes three stages: parsing, compiling and execution; 2) During the execution process, the engine will perform dynamic optimization, such as inline cache and hidden classes; 3) Best practices include avoiding global variables, optimizing loops, using const and lets, and avoiding excessive use of closures.

Python vs. JavaScript: The Learning Curve and Ease of UsePython vs. JavaScript: The Learning Curve and Ease of UseApr 16, 2025 am 12:12 AM

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

Python vs. JavaScript: Community, Libraries, and ResourcesPython vs. JavaScript: Community, Libraries, and ResourcesApr 15, 2025 am 12:16 AM

Python and JavaScript have their own advantages and disadvantages in terms of community, libraries and resources. 1) The Python community is friendly and suitable for beginners, but the front-end development resources are not as rich as JavaScript. 2) Python is powerful in data science and machine learning libraries, while JavaScript is better in front-end development libraries and frameworks. 3) Both have rich learning resources, but Python is suitable for starting with official documents, while JavaScript is better with MDNWebDocs. The choice should be based on project needs and personal interests.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools