Home >Web Front-end >Vue.js >An in-depth analysis of the ultimate anti-shake/throttling in Vue3

An in-depth analysis of the ultimate anti-shake/throttling in Vue3

青灯夜游
青灯夜游forward
2023-02-10 19:40:252730browse

This article brings you the ultimate anti-shake/throttle in Vue 3 (including common methods of anti-shake/throttle). This article will not only describe the original anti-shake or throttling methods. , will also bring a new packaging method, which is simpler and clearer to use.

An in-depth analysis of the ultimate anti-shake/throttling in Vue3

In the front-end development process, the process involving interaction with the user basically needs to be processed. The normal operation is to add anti-shake at the corresponding position. Or throttling.

Add anti-shake or throttling functions: first, to prevent users from frequent operations; second, to save certain server resources and reduce resource waste.

Anti-shake or throttling principle


Anti-shake (debounce)

If the user operates multiple times frequently, the last time will prevail. Of course, the first time can also be used as the basis for data updates or network resource requests to eliminate redundant operations or reduce a certain amount of waste of request resources. [Related recommendations: vuejs video tutorial, web front-end development

Sample code

function debounce (fn, delay = 300){
    let timer = null
    return function (...args) {
        clearTimeout(timer)
        timer = setTimeout(()=>{
            fn.call(this, ...args)
        }, delay);
    }
}

Use

debounce(()=> count += 1, 1000)

Throttle (throttle)

Within a certain time range, if the user triggers multiple times, it will only be executed once to prevent the user from Purpose of frequent operations.

Sample Code

let timer = null
function throttle (fn, delay = 300) {
    if(timer == null){
        timer = setTimeout(() => {
            fn()

            clearTimeout(timer)
            timer = null
        }, delay);
    }
}

Usage

throttle(()=> count += 1, 1000)

Environment Description


  • vue 3

  • vite

New package


Here I divide it into two Let’s talk about each module. One is anti-shake; the other is throttling.

Although the difference between the two is not very big, there is still a difference. Get in the car, guys.

Debounce

Let’s first look at the common package contents.

Common encapsulation-1

Code

function debounce (fn, delay = 300){
    let timer = null
    return function (...args) {
        if(timer != null){
            clearTimeout(timer)
            timer = null
        }
        timer = setTimeout(()=>{
            fn.call(this, ...args)
        }, delay);
    }
}

Usage

const addCount = debounce(()=> count.value += 1, 1000)

Common encapsulation-2

Code

let timer = null
function debounce (fn, delay = 1000){
    if(timer != null){
        clearTimeout(timer)
        timer = null
    }
    timer = setTimeout(fn, delay)
}

Use

const addCount = () => debounce(()=> count.value += 1, 1000)

New package

Here we need to use the ## in vue 3 #customRef to implement our new approach. I won’t write in detail here. I add comments directly above each line of code. I believe my friend you can understand.

Code

// 从 vue 中引入 customRef 和 ref
import { customRef, ref } from "vue"

// data 为创建时的数据
// delay 为防抖时间
function debounceRef (data, delay = 300){
    // 创建定时器
    let timer = null;
    // 对 delay 进行判断,如果传递的是 null 则不需要使用 防抖方案,直接返回使用 ref 创建的。
    return delay == null 
        ? 
        // 返回 ref 创建的
        ref(data)
        : 
        // customRef 中会返回两个函数参数。一个是:track 在获取数据时收集依赖的;一个是:trigger 在修改数据时进行通知派发更新的。
        customRef((track, trigger) => {
            return {
                get () {
                    // 收集依赖
                    track()
                    // 返回当前数据的值
                    return data
                },
                set (value) {
                    // 清除定时器
                    if(timer != null){
                        clearTimeout(timer)
                        timer = null
                    }
                    // 创建定时器
                    timer = setTimeout(() => {
                        // 修改数据
                        data = value;
                        // 派发更新
                        trigger()
                    }, delay)
                }
            }
        })
}

Use

// 创建
const count = debounceRef(0, 300)

// 函数中使用
const addCount = () => {
  count.value += 1
}

// v-model 中使用
<input type="text" v-model="count">

throttle

We are still the same, first See common package contents.

Common encapsulation-1

Code

let timer = null
function throttle (fn, delay = 300) {
    if(timer == null){
        timer = setTimeout(() => {
            fn()

            clearTimeout(timer)
            timer = null
        }, delay);
    }
}

Usage

const addCount = () => throttle(()=> count.value += 1, 1000)

Common encapsulation-2

Code

function throttle (fn, delay = 300) {
    let timer = null
    return function (...args) {
        if(timer == null){
            timer = setTimeout(() => {
                fn.call(this, ...args)
    
                clearTimeout(timer)
                timer = null
            }, delay);
        }
    }
}

Use

const addCount = throttle(()=> count.value += 1, 1000)

New package

Throttling and anti-shake are similar in packaging and use.

Code

// data 为创建时的数据
// delay 为节流时间
function throttleRef (data, delay = 300){
    // 创建定时器
    let timer = null;
    // 对 delay 进行判断,如果传递的是 null 则不需要使用 节流方案,直接返回使用 ref 创建的。
    return delay == null 
        ? 
        // 返回 ref 创建的
        ref(data)
        : 
        // customRef 中会返回两个函数参数。一个是:track 在获取数据时收集依赖的;一个是:trigger 在修改数据时进行通知派发更新的。
        customRef((track, trigger) => {
            return {
                get () {
                    // 收集依赖
                    track()
                    // 返回当前数据的值
                    return data
                },
                set (value) {
                    // 判断
                    if(timer == null){
                        // 创建定时器
                        timer = setTimeout(() => {
                            // 修改数据
                            data = value;
                            // 派发更新
                            trigger()
                            // 清除定时器
                            clearTimeout(timer)
                            timer = null
                        }, delay)
                    }
                    
                }
            }
        })
}

Use

// 创建
const count = debounceRef(0, 300)

// 函数中使用
const addCount = () => {
  count.value += 1
}

// v-model 中使用
<input type="text" v-model="count">

Summary


The above is the ultimate defense in

Vue 3 Shake/throttling (including common methods of anti-shaking/throttling) The entire content of this article. If there are any shortcomings or if you have a better way or other unique insights, please feel free to comment and send a private message.

Of course, my friend, you have learned another trick. You can like, follow and comment.

I hope this article will be helpful to the friends who are reading.

Friends who want to know how to implement the same solution in

vue 2 can click here? Implementing CustomRef method anti-shake/throttling in Vue 2

(Learning video sharing:

vuejs introductory tutorial, Basic programming video)

The above is the detailed content of An in-depth analysis of the ultimate anti-shake/throttling in Vue3. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:juejin.cn. If there is any infringement, please contact admin@php.cn delete