欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  web前端

函数节流与防抖的含义

程序员文章站 2022-03-17 19:46:47
...


function debounce(fn, delay, immediate){
    var timeout,
        args,
        context,
        timestamp,
        result;    
        var later = function(){
        var last = Date.now() - timestamp;       
        if(last < delay && last >= 0){
            timeout = setTimeout(later, delay - last);
        }else{
            timeout = null;            
            if(!immediate){
                result = fn.apply(context, args);                
                if(!timeout){
                    context = args = null;
                }
            }
        }
    };    return function(){
        context = this;
        args = arguments;
        timestamp = Date.now();
        console.log(timestamp);        
        var callNow = immediate && !timeout;        
        if(!timeout){
            timeout = setTimeout(later, delay);
        }        if(callNow){
            result = fn.apply(context, args);
            context = args = null;
        }        return result
    }
};function throttle(method , duration ,delay ){
    var timer = null, 
        // 记录下开始执行函数的时间
        begin = new Date();    
        return function(){
        var context = this, 
            args = arguments, 
            // 记录下当前时间
            current = new Date();        // 函数节流里的思路
        clearTimeout(timer);        // 记录下的两个时间相减再与duration进行比较
        if(current-begin >= duration){
             method.apply(context , args);
             begin = current;
        }else{  
            timer = setTimeout(function(){
                method.apply(context , args);
            } , delay);
        }
    }
}
window.onresize = throttle(function(){console.log('resize')},1000,500)

以上就是函数节流与防抖的含义的详细内容,更多请关注其它相关文章!