2
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

[JavaScript] async 中にawait でキー入力待ちする

Posted at

async関数中にボタンを押すまで処理を止める例。
ほぼ使うときないけどメモ。

html
<button id="next-btn">next</button>
<script>
  function waitClick(btn) {
    return new Promise((resolve, reject) => {
      btn.onclick = () => resolve()
      btn.onerror = e => reject(e)
    })
  }

  (async () => {
    let n = 0
    const nextButton = document.getElementById('next-btn')
    while (n < 10) {
      await waitClick(nextButton)
      console.log(n++)
    }
    console.log('done')
  })()
  /** 出力
  0
  1
  2
  3
  4
  5
  6
  7
  8
  9
  done
  */
</script>
2
0
0

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
2
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?