惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

T
Threatpost
博客园 - 叶小钗
T
The Blog of Author Tim Ferriss
Recent Announcements
Recent Announcements
D
DataBreaches.Net
The Cloudflare Blog
阮一峰的网络日志
阮一峰的网络日志
罗磊的独立博客
奇客Solidot–传递最新科技情报
奇客Solidot–传递最新科技情报
N
Netflix TechBlog - Medium
Microsoft Azure Blog
Microsoft Azure Blog
Microsoft Security Blog
Microsoft Security Blog
B
Blog
U
Unit 42
有赞技术团队
有赞技术团队
博客园 - 聂微东
GbyAI
GbyAI
宝玉的分享
宝玉的分享
F
Full Disclosure
freeCodeCamp Programming Tutorials: Python, JavaScript, Git & More
MyScale Blog
MyScale Blog
Jina AI
Jina AI
Martin Fowler
Martin Fowler
IT之家
IT之家
酷 壳 – CoolShell
酷 壳 – CoolShell
D
Docker
P
Proofpoint News Feed
A
About on SuperTechFans
I
InfoQ
博客园 - 【当耐特】
C
Check Point Blog
Threat Intelligence Blog | Flashpoint
Threat Intelligence Blog | Flashpoint
P
Privacy & Cybersecurity Law Blog
T
Threat Research - Cisco Blogs
Y
Y Combinator Blog
Project Zero
Project Zero
WordPress大学
WordPress大学
小众软件
小众软件
AWS News Blog
AWS News Blog
博客园 - 司徒正美
T
The Exploit Database - CXSecurity.com
L
LINUX DO - 热门话题
I
Intezer
Engineering at Meta
Engineering at Meta
C
CXSECURITY Database RSS Feed - CXSecurity.com
J
Java Code Geeks
T
Tenable Blog
Cyber Security Advisories - MS-ISAC
Cyber Security Advisories - MS-ISAC
Last Week in AI
Last Week in AI
C
CERT Recently Published Vulnerability Notes

Dmitri Pavlutin Blog

Pure Functions in JavaScript: A Beginner's Guide Record Type in TypeScript: A Quick Intro How to Write Comments in React: The Good, the Bad and the Ugly 4 Ways to Create an Enum in JavaScript React forwardRef(): How to Pass Refs to Child Components TypeScript Function Types: A Beginner's Guide How to Use v-model to Access Input Values in Vue Mastering Vue refs: From Zero to Hero Environment Variables in JavaScript: process.env 5 Must-Know Differences Between ref() and reactive() in Vue How to Destructure Props in Vue (Composition API) Triangulation in Test-Driven Development How to Use nextTick() in Vue Programming to Interface Vs to Implementation A Smarter JavaScript Mapper: array.flatMap() Array Grouping in JavaScript: Object.groupBy() How to Access ES Module Metadata using import.meta JSON Modules in JavaScript How to Trim Strings in JavaScript TypeScript Function Overloading How to Show/Hide Elements in Vue Sparse vs Dense Arrays in JavaScript How to Fill an Array with Initial Values in JavaScript Covariance and Contravariance in TypeScript What are Higher-Order Functions in JavaScript? How to Use TypeScript with React Components Index Signatures in TypeScript How to Use React useReducer() Hook unknown vs any in TypeScript A Guide to React Context and useContext() Hook How to Use Promise.any() 2 Ways to Remove a Property from an Object in JavaScript 'return await promise' vs 'return promise' in JavaScript How to Use Promise.allSettled() How to Use fetch() with JSON JavaScript Promises: then(f,f) vs then(f).catch(f) What is a Promise in JavaScript? How to Use Promise.all() A Simple Guide to Component Props in React Don't Stop Me Now: How to Use React useTransition() hook A Simple Explanation of JavaScript Variables: const, let, var ES Modules Dynamic Import How to Memoize with React.useMemo() How to Cleanup Async Effects in React Why Math.max() Without Arguments Returns -Infinity How to Debounce and Throttle Callbacks in React Don't Confuse Function Expressions and Function Declarations in JavaScript How to Use ES Modules in Node.js Solving a Mystery Behavior of parseInt() in JavaScript How to Use Array Reduce Method in JavaScript 3 Ways to Merge Arrays in JavaScript A Guide to Jotai: the Minimalist React State Management Library The Difference Between Values and References in JavaScript How to Implement a Queue in JavaScript A Helpful Algorithm to Determine "this" value in JavaScript React useRef() Hook Explained in 3 Steps 7 Interview Questions on "this" keyword in JavaScript. Can You Answer Them? How to Greatly Enhance fetch() with the Decorator Pattern 7 Interview Questions on JavaScript Closures. Can You Answer Them? What's a Method in JavaScript? array.sort() Does Not Simply Sort Numbers in JavaScript How to Solve the Infinite Loop of React.useEffect() The New Array Method You'll Enjoy: array.at(index) What's the Difference between DOM Node and Element? Why Promises Are Faster Than setTimeout()? Everything About Callback Functions in JavaScript How React Updates State 5 Mistakes to Avoid When Using React Hooks 5 Best Practices to Write Quality JavaScript Variables Type checking in JavaScript: typeof and instanceof operators 3 Ways to Check if a Variable is Defined in JavaScript React Forms Tutorial: Access Input Values, Validate, Submit Forms Prototypal Inheritance in JavaScript How to Timeout a fetch() Request How to Learn JavaScript If You're a Beginner A Simple Explanation of React.useEffect() A Simple Explanation of JavaScript Iterators How to Use React Controlled Inputs Everything about null in JavaScript How to Use Fetch with async/await Getting Started with Arrow Functions in JavaScript An Interesting Explanation of async/await in JavaScript Front-end Architecture: Stable and Volatile Dependencies Is it Safe to Compare JavaScript Strings? How to Access Object's Keys, Values, and Entries in JavaScript What Actually is a String in JavaScript? 3 Ways to Shallow Clone Objects in JavaScript (w/ bonuses) Checking if an Array Contains a Value in JavaScript JavaScript Event Delegation: A Beginner's Guide How to Parse URL in JavaScript: hostname, pathname, query, hash 3 Ways to Detect an Array in JavaScript How to Get the Screen, Window, and Web Page Sizes in JavaScript 3 Ways to Check If an Object Has a Property/Key in JavaScript How to Compare Objects in JavaScript Object.is() vs Strict Equality Operator in JavaScript Own and Inherited Properties in JavaScript 5 Differences Between Arrow and Regular Functions How to Use Object Destructuring in JavaScript Your Guide to React.useCallback() 5 JavaScript Scope Gotchas
How to Debounce and Throttle Callbacks in Vue
Dmitri Pavlutin · 2021-11-12 · via Dmitri Pavlutin Blog

Listening for often occurring events like user typing into the input field, window resize, scroll, intersection observer events etc. requires precaution.

These events could occur so often, e.g. a few times per second, that invoking an action like a fetch request on every event isn't a wise approach.

What you could do is slow down the execution of the event handlers. Such amortizing techniques are debouncing and throttling.

In this post, you'll find how to debounce and throttle watchers and event handlers in Vue components (both in composition and options API).

1. Debouncing a watcher

Let's start with a simple component, where your task is to log to console the value user introduces into a text input:


<script setup>

import { ref, watch } from 'vue'

const value = ref('')

watch(value, () => {

console.log("Value changed: ", value.value);

})

</script>

<template>

<input v-model="value" type="text" />

<p>{{ value }}</p>

</template>


Open the demo.

Options API


<script>

export default {

data() {

return {

value: "",

};

},

watch: {

value(newValue, oldValue) {

console.log("Value changed: ", newValue);

}

}

};

</script>

<template>

<input v-model="value" type="text" />

<p>{{ value }}</p>

</template>


Open the demo.

Open the demo and type a few characters into the input. Each time you type, the value is logged to the console. Logging is implemented using a watcher on the value.

Let's debounce the callback to reduce the rate of its execution. The idea is to create a debounced function, then invoke that function inside the watcher.

I use a debounce implementation from 'lodash.debounce', but you can use whatever implementation you like.

Let's update the component with debouncing:


<script setup>

import { ref, watch, onBeforeUnmount } from "vue";

import debounce from "lodash.debounce";

const value = ref("");

const debouncedWatch = debounce(() => {

console.log('New value:', value.value);

}, 500);

watch(value, debouncedWatch);

onBeforeUnmount(() => {

debouncedWatch.cancel();

})

</script>

<template>

<input v-model="value" type="text" />

<p>{{ value }}</p>

</template>


Open the demo.

Options API


<script>

import debounce from "lodash.debounce";

export default {

data() {

return {

value: "",

};

},

watch: {

value(...args) {

this.debouncedWatch(...args);

},

},

created() {

this.debouncedWatch = debounce((newValue, oldValue) => {

console.log('New value:', newValue);

}, 500);

},

beforeUnmount() {

this.debouncedWatch.cancel();

},

};

</script>

<template>

<input v-model="value" type="text" />

<p>{{ value }}</p>

</template>


Open the demo.

If you open the demo you'd notice that from the user's perspective little changed: you can still introduce characters as you were in the previous example.

But there's a change: the component logs to console the new value only if 500ms has passed since the last typing. That's debouncing in action.

Debouncing of a watcher is implemented in 3 simple steps:

  1. Create the debounced callback and assign it to a variable : const debouncedWatch = debounce(..., 500).

  2. Assign the debounced callback to watch API callback watch(value, debouncedWatch)

  3. Finally, make onBeforeUnmount() cancel debouncedWatch.cancel() any pending executions of the debounced function right before unmounting the component.

In the same way, you can debounce watch callbacks of any data property. Then you are safe to execute inside the debounced callback relatively heavy operations like data fetching, expensive DOM manipulations, and more.

2. Debouncing an event handler

The section above has shown how to debounce watchers, but what about regular event handlers?

Let's reuse again the example when the user enters data into the input field, but this time attach an event handler to the input.

As usual, if you don't perform any amortization, the changed value is logged to console every time the user types:


<script setup>

const handler = (event) => {

console.log('New value:', event.target.value);

}

</script>

<template>

<input v-on:input="handler" type="text" />

</template>


Open the demo.

Options API


<script>

export default {

methods: {

handler(event) {

console.log('New value:', event.target.value);

}

}

};

</script>

<template>

<input v-on:input="handler" type="text" />

</template>


Open the demo.

Open the demo and type a few characters into the input. Look at the console: you'd notice that the console updates each time you type.

Again, that's not always convenient if you want to perform some relatively heavy operations with the input value, e.g. doing a fetch request.

Let's debounce the event handler:


<script setup>

import { onBeforeUnmount } from "vue";

import debounce from "lodash.debounce";

const debouncedHandler = debounce(event => {

console.log('New value:', event.target.value);

}, 500);

onBeforeUnmount(() => {

debouncedHandler.cancel();

});

</script>

<template>

<input v-on:input="debouncedHandler" type="text" />

</template>


Open the demo.

Options API


<template>

<input v-on:input="debouncedHandler" type="text" />

</template>

<script>

import debounce from "lodash.debounce";

export default {

created() {

this.debouncedHandler = debounce(event => {

console.log('New value:', event.target.value);

}, 500);

},

beforeUnmount() {

this.debouncedHandler.cancel();

}

};

</script>


Open the demo.

Open the demo and type a few characters. The component logs to console the new value only if 500ms has passed since the last typing. Again, debouncing works!

Debouncing the event handler is implemented in 3 easy steps:

  1. Create the debounced callback const debouncedHandler = debounce(event => {...}, 500).

  2. Assign debouncedHandler to v-on:input:


<input v-on:input="debouncedHandler" type="text" />


  1. Finally, before unmounting, call debouncedHandler.cancel() to cancel any pending executions.

On a side note, the examples were using the debouncing technique. However, the same approach can be used to create throttled functions.

3. A word of caution (options API only)

You might be wondering: why not make the debounced function as a method directly on the component options, and then use the method as an event handler inside the template?


// ...

methods: {

// Why not?

debouncedHandler: debounce(function () { ... }}, 500)

}

// ...


That would be an easier approach than creating debounced functions as properties on the instance.

For example:


<template>

<input v-on:input="debouncedHandler" type="text" />

</template>

<script>

import debounce from "lodash.debounce";

export default {

methods: {

// Don't do this!

debouncedHandler: debounce(function(event) {

console.log('New value:', event.target.value);

}, 500)

}

};

</script>


Open the demo.

Instead of creating a debounced callback inside the created() hook, this time you assigned the debounced callback to the methods.debouncedHandler.

And if you open the demo, it works!

The problem is that the options object exported from the component using export default { ... }, including the methods, are going to be reused by all the instances of the component.

In case if the web page has 2 or more instances of the component, then all the components will use the same debounced function methods.debouncedHandler — and the debouncing could glitch.

4. Conclusion

In Vue, you can easily apply the debouncing and throttling techniques to callbacks of watchers and event handlers.

The main approach is to create the debounced or throttled callback:


// ...

const debouncedCallback = debounce((...args) => {

// The debounced callback

}, 500);

// ...


A) Then call the debounced instance either inside the watcher:


// ...

watch(myRef, debouncedCallback)

// ...


B) or set as an event handler inside the template:


<template>

<input v-on:input="debouncedCallback" type="text" />

</template>


Then, each time the debouncedCallback(...args) is invoked, even at very fast rates, the callback that it wraps is going to be amortized.

Also do not forget to cancel any pending debounced or throttled executions when the component unmounts:


onBeforeUnmount(() => {

debouncedCallback.cancel();

});


Do you still have questions about debouncing and throttling in Vue? Ask a question!