0
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 3 years have passed since last update.

非同期処理を待機して一番最後に呼ばれたものだけ実行する

Posted at

キー入力に対してインクリメントに動作するAPI呼び出しの待機処理などに使えるパターンです。
setTimeoutで遅延実行させている間に次の呼び出しがあった場合は、clearTimeoutで前回の呼び出しをキャンセルするので、最後に呼ばれたものだけが実行されます。

非同期処理をそのまま実行する例

index1.js
const data = ['a', 'b', 'c', 'd', 'e'];

const randomInt = function(min, max) {
  return Math.floor( Math.random() * (max + 1 - min) ) + min;
};
const process = name => {
  setTimeout(() => {
    console.log('process:' + name);
  }, randomInt(1000, 3000));
}

data.forEach((value) => {
  process(value)
  console.log(value);
})

// 実行結果
// a
// b
// c
// d
// e
// process:e
// process:d
// process:b
// process:a
// process:c

非同期処理を待機して一番最後に呼ばれたものだけ実行する例

index3.js
const data = ['a', 'b', 'c', 'd', 'e'];

const randomInt = function(min, max) {
  return Math.floor( Math.random() * (max + 1 - min) ) + min;
};

const process = name => {
  setTimeout(() => {
    console.log('process:' + name);
  }, randomInt(1000, 3000));
}


let timeoutId;
data.forEach((value) => {
  clearTimeout(timeoutId);
  timeoutId = setTimeout(() => {
    process(value)
  }, 1000)
  console.log(value);
})

// 実行結果
// a
// b
// c
// d
// e
// process:e

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