跳至主要内容

useTimeout

在给定时间后更新值。

Usage

即時編輯器

function Demo() {
  const [isPending, start, cancel] = useTimeout(5000);

  return (
    <div>
      <div>等待中:{JSON.stringify(isPending)}</div>
      <button
        onClick={() => {
          start();
        }}
      >
        重新開始
      </button>
      <button
        onClick={() => {
          cancel();
        }}
      >
        取消
      </button>
    </div>
  );
};

結果
等待中:true

API

useTimeout

Returns

Stoppable: 包含以下元素的元組:

  • 是否等待定時器執行。
  • 設定定時器。
  • 取消定時器。

Arguments

參數名描述類型預設值
ms间隔时间number | undefined-
options-UseTimeoutOptions | undefined-

UseTimeoutOptions

參數名描述類型預設值
immediate立即设置定时器booleantrue
Scrimba
Scrimba merges the IDE and video so you’ll get coding faster. Start free and level-up in frontend, fullstack and AI.
Start Free