
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() 函数,但是你可以使用 async 和 await 创建自定义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!
Understanding the JavaScript Engine: Implementation DetailsApr 17, 2025 am 12:05 AMUnderstanding 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 UseApr 16, 2025 am 12:12 AMPython 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 ResourcesApr 15, 2025 am 12:16 AMPython 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.
From C/C to JavaScript: How It All WorksApr 14, 2025 am 12:05 AMThe shift from C/C to JavaScript requires adapting to dynamic typing, garbage collection and asynchronous programming. 1) C/C is a statically typed language that requires manual memory management, while JavaScript is dynamically typed and garbage collection is automatically processed. 2) C/C needs to be compiled into machine code, while JavaScript is an interpreted language. 3) JavaScript introduces concepts such as closures, prototype chains and Promise, which enhances flexibility and asynchronous programming capabilities.
JavaScript Engines: Comparing ImplementationsApr 13, 2025 am 12:05 AMDifferent JavaScript engines have different effects when parsing and executing JavaScript code, because the implementation principles and optimization strategies of each engine differ. 1. Lexical analysis: convert source code into lexical unit. 2. Grammar analysis: Generate an abstract syntax tree. 3. Optimization and compilation: Generate machine code through the JIT compiler. 4. Execute: Run the machine code. V8 engine optimizes through instant compilation and hidden class, SpiderMonkey uses a type inference system, resulting in different performance performance on the same code.
Beyond the Browser: JavaScript in the Real WorldApr 12, 2025 am 12:06 AMJavaScript's applications in the real world include server-side programming, mobile application development and Internet of Things control: 1. Server-side programming is realized through Node.js, suitable for high concurrent request processing. 2. Mobile application development is carried out through ReactNative and supports cross-platform deployment. 3. Used for IoT device control through Johnny-Five library, suitable for hardware interaction.
Building a Multi-Tenant SaaS Application with Next.js (Backend Integration)Apr 11, 2025 am 08:23 AMI built a functional multi-tenant SaaS application (an EdTech app) with your everyday tech tool and you can do the same. First, what’s a multi-tenant SaaS application? Multi-tenant SaaS applications let you serve multiple customers from a sing
How to Build a Multi-Tenant SaaS Application with Next.js (Frontend Integration)Apr 11, 2025 am 08:22 AMThis article demonstrates frontend integration with a backend secured by Permit, building a functional EdTech SaaS application using Next.js. The frontend fetches user permissions to control UI visibility and ensures API requests adhere to role-base


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Safe Exam Browser
Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

Zend Studio 13.0.1
Powerful PHP integrated development environment

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.

VSCode Windows 64-bit Download
A free and powerful IDE editor launched by Microsoft

WebStorm Mac version
Useful JavaScript development tools







