throttle和debounce簡單實現

看風景就發表於2016-12-19
function debounce(delay,fn){
    var timer;
    return function(){
        var ctx = this,args = arguments;
        clearTimeout(timer);
        timer = setTimeout(function(){
            fn.apply(ctx,args);
        },delay);
    }
}

function throttle(interval,fn){
    var last = 0;
    return function(){
        var cur = +new Date(),ctx = this,args = arguments;
        if(cur - last > interval){
            fn.apply(ctx,args);
            last = cur;
        }
    }
}

 

 

參考:http://www.cnblogs.com/fsjohnhuang/p/4147810.html

相關文章