API 浏览器
useTimeout 组合
Quasar v2.15+

useTimeout() 可组合项的作用域与原生 setTimeout() 类似,但也存在一些关键区别。一旦触发 setTimeout(fn, delay) 函数,无论如何,它都会在指定的延迟时间后执行。另一方面,useTimeout() 可以是 “cancelled”。你还可以在超时到期之前覆盖正在执行的函数。

¥The useTimeout() composable is similar in scope with the native setTimeout(), with some key differences. Once you trigger a setTimeout(fn, delay) it will get executed after the specified delay no matter what. The useTimeout() on the other hand, can be “cancelled”. You can also override the executing Function before the timeout expires.

换句话说,如果你想在延迟后调度某个函数,但你可能希望在延迟发生之前覆盖它甚至取消它,那么这就是适合你的可组合项。

¥In other words, if you want to schedule a function after a delay but you might want to override it or even cancel it before the delay happens, this is the composable for you.

useTimeout 可组合函数也会在组件销毁时自动取消(如果已注册且仍处于待处理状态)。

¥The useTimeout composable also automatically cancels (if it was registered and still pending) when your component gets destroyed.

语法(Syntax)

¥Syntax

import { useTimeout } from 'quasar'

setup () {
  const {
    registerTimeout,
    removeTimeout
  } = useTimeout()

  // ...
}
function useTimeout(): {
  registerTimeout(fn: () => void, delay?: string | number): void;
  removeTimeout(): void;
};

示例(Example)

¥Example

import { useTimeout } from 'quasar'

setup () {
  const { registerTimeout } = useTimeout()

  function onSomeEvent (param) {
    registerTimeout(() => {
      console.log('param is', param)
    }, 2000) // in 2 seconds
  }

  // ...

  // You can call onSomeEvent() multiple
  // times in a row and only the last
  // registered Function will run when it
  // is time for it

  // Note that the delay is reset each
  // time you register/override the timeout
}

如果每个组件需要多个 useTimeout(),只需重命名返回对象的函数即可:

¥Should you need more than one useTimeout() per component, simply rename the functions of the returned object:

const {
  registerTimeout: registerFirstTimeout,
  removeTimeout: removeFirstTimeout
} = useTimeout()

const {
  registerTimeout: registerSecondTimeout,
  removeTimeout: removeSecondTimeout
} = useTimeout()