Skip to content
On this page

useTimeout

The setTimeout.

Parameters

typescript
import { useTimeout } from '@elonehoo/pistachio'

useTimeout(fn, delay)
import { useTimeout } from '@elonehoo/pistachio'

useTimeout(fn, delay)
ParametersTypeRequiredDefaultDescription
fnFunctiontrueA function to be executed after the timer expires.
delaynumberfalse0 The time, in milliseconds (thousandths of a second), the timer should wait before the specified function is executed.

State

The useTimeout function exposes the following reactive state:

typescript
import { useTimeout } from '@elonehoo/pistachio'

const { ready } = useTimeout(fn, delay)
import { useTimeout } from '@elonehoo/pistachio'

const { ready } = useTimeout(fn, delay)
StateTypeDescription
readyRef<boolean | null>current timeout state:
 false - pending
 true - called
 null - canceled

Methods

The useTimeout function exposes the following methods:

typescript
import { useTimeout } from '@elonehoo/pistachio'

const { cancel } = useTimeout(fn, delay)
import { useTimeout } from '@elonehoo/pistachio'

const { cancel } = useTimeout(fn, delay)
SignatureDescription
cancelcancel the timeout

Example

vue
<script setup lang="ts">
import { useTimeout } from '@elonehoo/pistachio'

let cancelTimeout

function show() {
  const { cancel } = useTimeout(() => {
    alert('useTimeout callback invoked')
  }, 2000)
  cancelTimeout = cancel
}

function cancel() {
  cancelTimeout()
}
</script>

<template>
  <div>
    <p />
    <button @click="show">
      Show an alert box after two seconds
    </button>
    <p />
    <button @click="cancel">
      Cancel alert before it happens
    </button>
  </div>
</template>
<script setup lang="ts">
import { useTimeout } from '@elonehoo/pistachio'

let cancelTimeout

function show() {
  const { cancel } = useTimeout(() => {
    alert('useTimeout callback invoked')
  }, 2000)
  cancelTimeout = cancel
}

function cancel() {
  cancelTimeout()
}
</script>

<template>
  <div>
    <p />
    <button @click="show">
      Show an alert box after two seconds
    </button>
    <p />
    <button @click="cancel">
      Cancel alert before it happens
    </button>
  </div>
</template>

Released under the MIT License.