In Vue3 projects, we often need to use anti-shake and throttling functions to optimize performance. This article will introduce how to use TypeScript to wrap a global throttling function.
What is a throttling function
Throttling a function is a way to limit how often a function executes. It ensures that a function is executed only once within a certain period of time, even if it is called multiple times.
Why do you need a throttling function
In some high-frequency triggered events, such as window resize and scroll events, calling functions frequently will cause performance problems. This problem can be avoided by using the throttling function.
Encapsulates the global throttling function
In Vue3, we can implement a global throttling function by creating a plugin. First create a Throttle
class that takes a function and an interval as parameters and returns a function.
class Throttle {
private timer: number | null = null;
constructor(private fn: () => void, private interval: number) {
}
public run() {
if (this.timer !== null) return;
this.timer = window.setTimeout(() => {
this.fn();
this.timer = null;
}, this.interval);
}
}
Then create a plugin to Throttle
mount the class on Vue.prototype.
const throttlePlugin = {
install: (app: App) => {
app.config.globalProperties.$throttle = (fn: () => void, interval: number) => {
const throttle = new Throttle(fn, interval);
return () => throttle.run();
};
},
};
Finally use the plugin in the main.ts of the Vue3 project.
import {
createApp } from 'vue';
import App from './App.vue';
import throttlePlugin from './throttle';
const app = createApp(App);
app.use(throttlePlugin);
app.mount('#app');
Now we can use $throttle
the function globally.
export default {
methods: {
handleClick() {
this.$throttle(() => {
console.log('click event, throttled');
}, 1000)();
},
},
};
When the click event is triggered, $throttle
the function returns a new function, which will be executed after 1000ms.
Summarize
This article describes how to use TypeScript to encapsulate a global throttling function and use it in a Vue3 project. Hope this article is helpful to you.