Help us understand the problem. What is going on with this article?

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

はじめに

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();

さいごに

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

ren_matsushita
(17) iOS. App, Web Developer / React.js / RxSwift
Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
Comments
No comments
Sign up for free and join this conversation.
If you already have a Qiita account
Why do not you register as a user and use Qiita more conveniently?
You need to log in to use this function. Qiita can be used more conveniently after logging in.
You seem to be reading articles frequently this month. Qiita can be used more conveniently after logging in.
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
ユーザーは見つかりませんでした