Skip to content

useThrottleFn

Category
Last Changed
7 months ago

Throttle execution of a function. Especially useful for rate limiting execution of handlers on events like resize and scroll.

Throttle is a spring that throws balls: after a ball flies out it needs some time to shrink back, so it cannot throw any more balls unless it's ready.

Demo

Delay is set to 1000ms for this demo.

Button clicked: 0

Event handler called: 0

Usage

import { useThrottleFn } from '@vueuse/core'

const throttledFn = useThrottleFn(() => {
  // do something, it will be called at most 1 time per second
}, 1000)

document.addEventListener('resize', throttledFn)
import { useThrottleFn } from '@vueuse/core'

const throttledFn = useThrottleFn(() => {
  // do something, it will be called at most 1 time per second
}, 1000)

document.addEventListener('resize', throttledFn)
  • useThrottle
  • useThrottleFn
  • useDebounce
  • useDebounceFn

Type Declarations

/**
 * Throttle execution of a function. Especially useful for rate limiting
 * execution of handlers on events like resize and scroll.
 *
 * @param   fn             A function to be executed after delay milliseconds. The `this` context and all arguments are passed through, as-is,
 *                                    to `callback` when the throttled-function is executed.
 * @param   ms             A zero-or-greater delay in milliseconds. For event callbacks, values around 100 or 250 (or even higher) are most useful.
 *
 * @param [trailing=true] if true, call fn again after the time is up
 *
 * @param [leading=true] if true, call fn on the leading edge of the ms timeout
 *
 * @return  A new, throttled, function.
 */
export declare function useThrottleFn<T extends FunctionArgs>(
  fn: T,
  ms?: MaybeRef<number>,
  trailing?: boolean,
  leading?: boolean
): T
/**
 * Throttle execution of a function. Especially useful for rate limiting
 * execution of handlers on events like resize and scroll.
 *
 * @param   fn             A function to be executed after delay milliseconds. The `this` context and all arguments are passed through, as-is,
 *                                    to `callback` when the throttled-function is executed.
 * @param   ms             A zero-or-greater delay in milliseconds. For event callbacks, values around 100 or 250 (or even higher) are most useful.
 *
 * @param [trailing=true] if true, call fn again after the time is up
 *
 * @param [leading=true] if true, call fn on the leading edge of the ms timeout
 *
 * @return  A new, throttled, function.
 */
export declare function useThrottleFn<T extends FunctionArgs>(
  fn: T,
  ms?: MaybeRef<number>,
  trailing?: boolean,
  leading?: boolean
): T

Source

SourceDemoDocs

Contributors

Anthony Fu
Jakub Freisler
Roman Harmyder
wheat

Changelog

v6.5.0 on 9/25/2021
c0078 - feat(throttleFilter): add leading option (#771)
v6.4.0 on 9/17/2021
4a33e - feat(useThrottle): trailing option, useThrottledRefHistory updated (#760)
useThrottleFn has loaded