防抖

一、基本概念

避免用户的频繁触发,将一定时间内的操作合并为一次,并在给定时间以后只执行一次

二、实现

    function debounce1(fn,time){
        var timer = null
        return function(){
            clearTimeout(timer)
            timer = setTimeout(fn,time)
        }
    }

用户的两次操作间隔小于time时,只执行最后一次 

第一次点击触发操作

    function debounce2(fn,time){
        var timer = null
        return function(){
            clearTimeout(timer)
            if(timer){
                timer = setTimeout(function(){
                    fn()
                },time)
            } else {
                fn()
                timer = setTimeout(function(){
                    timer=null
                },time)
            }
        }
    }
    

  

原文地址:https://www.cnblogs.com/lhyhappy365/p/10301102.html