带立即执行的防抖函数

64 阅读1分钟
function debounceWithImmediate(func, wait = 800, immediate = true) {    
    let timer = null;    
    let immediatelyRun = false;    
    return function(...args) {        
        if (timer) {            
            clearTimeout(timer);            
            timer = null;        
        }        
        if (immediate) {            
            if (!immediatelyRun) {                
                immediatelyRun = true;                
                func.apply(this, args);            
            }            
            timer = setTimeout(() => {                
                immediatelyRun = false;                
                timer = null;            
            }, wait);        
        } else {            
            timer = setTimeout(() => {                
                func.apply(this, args);                
                timer = null;           
             }, wait);        
        }    
    }
}