异步/等待setTimeOut()中的延迟

时间:2020-04-22 20:54:42

标签: javascript async-await

我想构建一个页面,该页面在morse code中闪烁,并不断重复显示消息“ SOS”。

所以“---... ..---”

当我尝试运行以下代码时,它将引发错误:

Uncaught SyntaxError: Unexpected reserved word

我已经用<-- HERE标记了要引起闪烁的位置,并注释了这一行,因此代码至少可以编译。

如果我不能在这里延迟await,那么如何创建所需长度的闪烁?

const BODY = document.querySelector('body');
const AMOUNT = 3;

let timeOut = 0;
let dash = 1000;
let dot = 500;
let count = 0; // fake counter for infinite loop

const delay = (ms) => new Promise((res) => setTimeout(res, ms));

async function morse() {
  if (count < 1) {
    Array(AMOUNT) // clearer way for me to loop 'AMOUNT' number of times
      .fill()
      .map(() => {
        setTimeout(() => {
          BODY.style.backgroundColor = 'black';
          //   await delay(n); <--- HERE
          BODY.style.backgroundColor = 'white';
          console.log('dash');

          // invoke self for infinite loop
          morse();
        }, timeOut);
        timeOut += dash;
      });

    Array(AMOUNT)
      .fill()
      .map(() => {
        setTimeout(() => {
          BODY.style.backgroundColor = 'black';
          //   await delay(n); <--- HERE
          BODY.style.backgroundColor = 'black';
          console.log('dot');
          morse();
        }, timeOut);
        timeOut += dot;
      });
}

2 个答案:

答案 0 :(得分:1)

您需要将 async 设置为setTimeout回调:

setTimeout(async() => {
          BODY.style.backgroundColor = 'black';
          await delay(0);
          BODY.style.backgroundColor = 'white';
          console.log('dash');

          // invoke self for infinite loop
          morse();
        }, timeOut);

答案 1 :(得分:1)

假设我们有以下内容:

const _body = document.querySelector('body');
const dash = () => _body.style.backgroundColor = 'lightblue';
const dot = () => _body.style.backgroundColor = 'lightpink';

const delay = (ms) => new Promise((res) => setTimeout(res, ms));

然后我们可以做:

delay(500).then(() => dash()).then(() => delay(1000).then(() => dot()))

...等等,您可以继续链接它们以获得所需的结果。

您可以将所有内容粘贴到控制台中,并且您的StackOverflow背景应呈蓝色和粉红色闪烁两次。

干杯! ?