1
0

More than 3 years have passed since last update.

遅延実行asyncのメモ

Last updated at Posted at 2019-11-18

asyncで遅延実行

ある実行のあとに、もう一つ実行させたい、そしてそのまた後に何秒後に実行

みたいなケースのときに活用した。

コード


  const test1 = () => {
   alert(1);
  }

  const test2 = () => {
   alert(2);
  }

  //////////////////////
  // 表示のタイミング
  //////////////////////
  async function delay() {
    try {
      //秒数と、関数を渡す
      await wait(1, test1());
      await wait(1, test2());
    } catch (err) {
      console.error(err);
    }
  }


  //////////////////////
  // 遅延実行
  //////////////////////
  const wait = (sec) => {
    return new Promise((resolve, reject) => {
      setTimeout(resolve, sec * 1000);
    });
  };

結果

test1()のalertが実行された1秒後に、test2()のalertが表示される
関数を渡すことで色々と応用できたので個人的メモ

async

超便利
もっとうまく書く方法があれば教えてほしい、、、、、

1
0
3

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0