1. 显式防抖

ultra-debounce 提供了 “debounce” 包装函数,可以实现任意js方法的防抖。

1.1. 普通方法的防抖

import {debounce} from "@zhoujianhui/ultra-debounce"

const debounceService = {
    debouncedMethod: debounce(() => {
        console.info("立即执行,1秒内不再重复执行");
    }, 1000, {leading: true, trailing: false})
}

此时快速点击按钮调用 “debounceService.debouncedMethod()” 方法,会发现只调用了一次。

debounce的语法为:

debounce(func, wait, options)

其中:

  • func:需要防抖的js方法
  • wait:延迟的时长,单位:毫秒
  • options:选项
    • leading:是否立即执行(可选,默认为:false)
    • trailing:是否在延迟到期后执行(可选,默认为:true)

1.2. API请求方法的防抖

如果js方法是一个调用远程API的方法,依然可以显示防抖。

import axios from "axios";
import {debounce} from "@zhoujianhui/ultra-debounce"
import {Result} from "@zhoujianhui/vip3-core";

const debounceService = {
    debouncedMethodRequest: debounce(async () => {
        try {
            const response = await axios.get("https://reqres.in/api/users/1")

            return Result.success("获取用户成功!").data(response.data).build()
        } catch (error) {
            return Result.error(`获取用户失败!具体原因:${error.message}`).build()
        }
    }, 1000, {leading: true, trailing: false})
}

此时快速点击按钮调用 “debounceService.debouncedMethodRequest()” 方法,会发现请求只发出一次,后续调用复用了第一次的结果。

显式请求

显式请求防抖

Copyright ©zhoujianhui all right reserved,powered by Gitbook更新时间: 2024-12-05 17:15:27

results matching ""

    No results matching ""