Skip to content

useDebounceFn

函数的执行去抖动。

¥Debounce execution of a function.

Debounce 是一个超载的服务员:如果你继续询问他,你的请求将被忽略,直到你停下来并给他一些时间考虑你最新的询问。

¥Debounce is an overloaded waiter: if you keep asking him your requests will be ignored until you stop and give him some time to think about your latest inquiry.

示例

Delay is set to 1000ms and maxWait is set to 5000ms for this demo.

Button clicked: 0

Event handler called: 0

用法

¥Usage

js
import { useDebounceFn } from '@vueuse/core'

const debouncedFn = useDebounceFn(() => {
  // do something
}, 1000)

window.addEventListener('resize', debouncedFn)

你还可以向此传递第三个参数,具有最大等待时间,类似于 洛达什去抖

¥You can also pass a 3rd parameter to this, with a maximum wait time, similar to lodash debounce

js
import { useDebounceFn } from '@vueuse/core'

// If no invokation after 5000ms due to repeated input,
// the function will be called anyway.
const debouncedFn = useDebounceFn(() => {
  // do something
}, 1000, { maxWait: 5000 })

window.addEventListener('resize', debouncedFn)

或者,你可以使用 Promise 操作获取函数的返回值。

¥Optionally, you can get the return value of the function using promise operations.

js
import { useDebounceFn } from '@vueuse/core'

const debouncedRequest = useDebounceFn(() => 'response', 1000)

debouncedRequest().then((value) => {
  console.log(value) // 'response'
})

// or use async/await
async function doRequest() {
  const value = await debouncedRequest()
  console.log(value) // 'response'
}

由于当开发者不需要返回值时,未处理的拒绝错误非常烦人,因此如果默认情况下取消函数,则 promise 不会被拒绝。你需要指定选项 rejectOnCancel: true 来捕获拒绝。

¥Since unhandled rejection error is quite annoying when developer doesn't need the return value, the promise will NOT be rejected if the function is canceled by default. You need to specify the option rejectOnCancel: true to capture the rejection.

js
import { useDebounceFn } from '@vueuse/core'

const debouncedRequest = useDebounceFn(() => 'response', 1000, { rejectOnCancel: true })

debouncedRequest()
  .then((value) => {
    // do something
  })
  .catch(() => {
    // do something when canceled
  })

// calling it again will cancel the previous request and gets rejected
setTimeout(debouncedRequest, 500)

¥Recommended Reading

类型声明

typescript
/**
 * Debounce execution of a function.
 *
 * @see https://vueuse.org/useDebounceFn
 * @param  fn          A function to be executed after delay milliseconds debounced.
 * @param  ms          A zero-or-greater delay in milliseconds. For event callbacks, values around 100 or 250 (or even higher) are most useful.
 * @param  options     Options
 *
 * @return A new, debounce, function.
 */
export declare function useDebounceFn<T extends FunctionArgs>(
  fn: T,
  ms?: MaybeRefOrGetter<number>,
  options?: DebounceFilterOptions,
): PromisifyFn<T>

源代码

源代码示例文档

变更日志

No recent changes

VueUse 中文网 - 粤ICP备13048890号