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()
函数,但是你可以使用 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!

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

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

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

How to use WebSocket and JavaScript to implement an online speech recognition system Introduction: With the continuous development of technology, speech recognition technology has become an important part of the field of artificial intelligence. The online speech recognition system based on WebSocket and JavaScript has the characteristics of low latency, real-time and cross-platform, and has become a widely used solution. This article will introduce how to use WebSocket and JavaScript to implement an online speech recognition system.

WebSocket and JavaScript: Key technologies for realizing real-time monitoring systems Introduction: With the rapid development of Internet technology, real-time monitoring systems have been widely used in various fields. One of the key technologies to achieve real-time monitoring is the combination of WebSocket and JavaScript. This article will introduce the application of WebSocket and JavaScript in real-time monitoring systems, give code examples, and explain their implementation principles in detail. 1. WebSocket technology

Introduction to how to use JavaScript and WebSocket to implement a real-time online ordering system: With the popularity of the Internet and the advancement of technology, more and more restaurants have begun to provide online ordering services. In order to implement a real-time online ordering system, we can use JavaScript and WebSocket technology. WebSocket is a full-duplex communication protocol based on the TCP protocol, which can realize real-time two-way communication between the client and the server. In the real-time online ordering system, when the user selects dishes and places an order

How to use WebSocket and JavaScript to implement an online reservation system. In today's digital era, more and more businesses and services need to provide online reservation functions. It is crucial to implement an efficient and real-time online reservation system. This article will introduce how to use WebSocket and JavaScript to implement an online reservation system, and provide specific code examples. 1. What is WebSocket? WebSocket is a full-duplex method on a single TCP connection.

JavaScript and WebSocket: Building an efficient real-time weather forecast system Introduction: Today, the accuracy of weather forecasts is of great significance to daily life and decision-making. As technology develops, we can provide more accurate and reliable weather forecasts by obtaining weather data in real time. In this article, we will learn how to use JavaScript and WebSocket technology to build an efficient real-time weather forecast system. This article will demonstrate the implementation process through specific code examples. We

JavaScript tutorial: How to get HTTP status code, specific code examples are required. Preface: In web development, data interaction with the server is often involved. When communicating with the server, we often need to obtain the returned HTTP status code to determine whether the operation is successful, and perform corresponding processing based on different status codes. This article will teach you how to use JavaScript to obtain HTTP status codes and provide some practical code examples. Using XMLHttpRequest

Usage: In JavaScript, the insertBefore() method is used to insert a new node in the DOM tree. This method requires two parameters: the new node to be inserted and the reference node (that is, the node where the new node will be inserted).

JavaScript is a programming language widely used in web development, while WebSocket is a network protocol used for real-time communication. Combining the powerful functions of the two, we can create an efficient real-time image processing system. This article will introduce how to implement this system using JavaScript and WebSocket, and provide specific code examples. First, we need to clarify the requirements and goals of the real-time image processing system. Suppose we have a camera device that can collect real-time image data
