2
2

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.

TypeScriptでキャンセル可能なsetTimeOut()関数を作る

Posted at

はじめに

TypeScriptを書いていてキャンセル可能なsetTimeOut関数が欲しいなと思ったので書きました。もっといい書き方があれば教えていただきたいです!!

実装

他にもいくつか方法はあると思いますが、今回は引数に遅延時間(duration)とコールバック関数を渡すと、実行開始の関数とキャンセル用の関数が帰ってくるような仕組みにしました。


const disposableTimeOut = (duration: number, callback: () => void): {
  on: () => Promise<void>,
  dispose: () => void,
} => {
  let timeOutId: NodeJS.Timeout | null;
  let resolve: () => void
  const on = () => new Promise<void>((_resolve) => {
    resolve = _resolve;
    timeOutId = setTimeout(() => {
      callback();
      timeOutId = null;
      resolve();
    }, duration)
  })
  const dispose = () => {
    if (timeOutId) {
      clearTimeout(timeOutId);
      timeOutId = null;
      resolve();
    }
  }

  return {
    on,
    dispose,
  }
}

使用例

const disposable = disposableTimeOut(1000, () => {
  console.log('1秒たったよ!! ワイワイ!!')
}

// タイムアウトしたい関数を実行する
await disposable.on();

// キャンセルしたいところでキャンセル(破棄)する
disposable.dispose();

さいごに

↑みたいな感じで動きます!!

2
2
2

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
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?