防抖节流方法

本文介绍了JavaScript中两种重要的性能优化技巧——防抖(debounce)和节流(throttle)函数的实现。防抖函数用于限制函数的频繁执行,而节流函数则控制函数在一定时间内只执行一次。通过引入这两个函数,可以有效防止短时间内重复请求,提高应用性能。示例代码展示了如何在实际场景如搜索输入中应用这些技术。
摘要由CSDN通过智能技术生成

为了优化性能,避免短时间重复请求

新建util.js文件

// 防抖函数

let debounce = function (func, delay){

        let timer;

        return function(){

                let _this = this;

                let args = arguments;

                if(timer) clearTimeout(timer);

                timer = setTimeout(()=>{

                        func.apply(_this,args);

                },delay);

        }

}

// 节流函数

let throttle = function(func, delay){

        let timeout;

        return function(){

                let _this = this;

                let args = arguments;

                if(!timeout){

                        timeout = setTimeout(()=>{

                                timeout = null;

                                func.apply(_this, args);

                        },delay)

                }

        }

}

export { debounce, throttle }

页面引用util.js

import { debounce } from '../../js/util.js'

searchInput: debounce(function(e){

        var value = e.detail.value

        if (value) {

                this.setData({

                        inputValue: value

                });

                this.getSearchList();

        }

},500),

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值