zoukankan      html  css  js  c++  java
  • 节流防抖学习与实践

    先看看概念

    函数防抖(debounce):

    在事件被触发n秒后再执行回调,如果在这n秒内又被触发,则重新计时;典型的案例就是输入搜索:输入结束后n秒才进行搜索请求,n秒内又输入的内容,就重新计时。像是两个人的对话,A在不停的balabala(持续触发),如果他说话的时候有停顿(一定间隔),但是停顿的时间不够长,就认为A没有说完, 当停顿时间超过一某个范围就认为A说完了,然后B开始回答(响应)。

    函数节流(throttle):

    规定在一个单位时间内,只能触发一次函数,如果这个单位时间内触发多次函数,只有第一次生效; 典型的案例就是鼠标不断点击触发,规定在n秒内多次点击只有一次生效。感觉像是去排队过安检,当人很多的时候(持续地要进门),安保会隔一段时间放进去几个进行安检(一定时间的间隔)。

    场景

    前提其实都是某个行为持续地触发,不同之处只要判断是要 优化到减少它的执行次数(throttle) 还是 只执行一次(debounce) 就行。

    实现(Vue mixin用法)

    //防抖
    let _d_timer = null;
    Vue.prototype.$debounce = (cb, delay) => {
        let that = this;
        if (!delay) {
            delay = 1000;
        }
        if (_d_timer) {
            clearTimeout(_d_timer);
        }
        _d_timer = setTimeout(function() {
            cb();
            _d_timer = null;
        }, delay)
    }
    
    
    //节流
    let throttle_canRun=true;
    Vue.prototype.$throttle=(cb,delay)=>{
        if(!throttle_canRun)    return;
        if(!delay)    delay=500;
        throttle_canRun=false;
        setTimeout(function(){
            throttle_canRun=true;
            cb();
        },delay)
    }

    页面应用

    onInput() {
        this.$debounce(()=>{
            uni.request({
                url: "https://vipshop.herokuapp.com/api/v1/product/",
                data: {
                    name: this.txt
                },
                success:(res)=> {
                    console.log(res)
                }
            })
        });
    },
    throttleHandle(){
        this.$throttle(function(){
            console.log(111)
        })
    }
  • 相关阅读:
    jsp+servlet+javabean实现ssh的mvc模式
    String类型数字始终保留两位小数
    关于truncate与checkident
    ajax实现mvc模式
    全面掌握IO(输入/输出流)
    搭建android开发环境
    org.w3c.dom(java dom)解析XML文档
    sql查询详解
    InstallShield 2012 Spring评估试用(1): 支持Windows 8和Windows Server 2012操作系统
    InstallShield 2012 Spring新功能试用(6): InstallScript工程支持64位组件(Components)
  • 原文地址:https://www.cnblogs.com/gitByLegend/p/11565432.html
Copyright © 2011-2022 走看看