Home > Web Front-end > JS Tutorial > Implementing sleep or wait using JavaScript

Implementing sleep or wait using JavaScript

青灯夜游
Release: 2021-01-27 19:14:12
forward
11315 people have browsed it

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}`)
}
Copy after login

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)
}
Copy after login

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)
Copy after login

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, "你好")
Copy after login

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)
Copy after login

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()
Copy after login

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)
Copy after login

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()
Copy after login

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

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

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

总结

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!

Related labels:
source:segmentfault.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template