wutai
wutai

Reputation: 39

Using throttle with Vue 3

I use lodash in a Vue 3 project, when I try to use the _.throttle in the setup function, it doesn't work. I writed a demo in the stackblitz.

<template>
  <div id="app">
    <button @click="handleClick">Click</button>
  </div>
</template>

<script>
import _ from 'lodash';

export default {
  name: 'App',
  setup() {
    const handleClick = () =>
      _.throttle(function () {
        console.log('hi');
      }, 2000);

    return {
      handleClick,
    };
  },
};
</script>

Upvotes: 1

Views: 2564

Answers (3)

I try to implement a function for generating wrappers to support Throttle and Debounce a function in TS without other libraries.

export function useThrottleFn<T extends any[]>(fn: Function, wait: number): (...args: T) => void {
  let timer: any
  return (...args: T) => {
    if (!timer) {
      fn(...args)
      timer = setTimeout(() => {
        clearTimeout(timer)
        timer = null
      }, wait)
    }
  }
}

Upvotes: 0

wutai
wutai

Reputation: 39

Okay, I have a solution now. My companion said that omit the () => can fix it, add the { trailing: false } is better.

const handleClick = _.throttle(function () { console.log('hi'); }, 2000, { trailing: false });

Upvotes: 2

Boussadjra Brahim
Boussadjra Brahim

Reputation: 1

You're missing to run the throttled function by adding the () :

  const handleClick = () =>
      _.throttle(function () {
        console.log('hi');
      }, 2000)();

or assign it to a variable then run it :

  const handleClick = () =>{
     let throttled= _.throttle(function () {
        console.log('hi');
      }, 2000);
     
     throttled();
   }

Upvotes: 0

Related Questions