1. 程式人生 > >[JS]防抖和節流

[JS]防抖和節流

以前不知道這些名詞,然後看了這篇文章知道了。

防抖(Debouncing)

像防抖還是很容易想到的,大概意思就是延時處理,然後如果在這段延時內又觸發了事件,則重新開始延時。

看程式碼最直觀啦。

// 簡單示例
window.addEventListener('resize',function(e){
    var t;
    return function(){
        if(t) clearTimeout(t);
        t = setTimeout(function(){
            // do something...
        },500);
    }
}());

節流(Throttling)

有的情況下,防抖是不能滿足需求的。

抄來程式碼

// 簡單的節流函式
function throttle(func, wait, mustRun) {
    var timeout,
        startTime = new Date();

    return function() {
        var context = this,
            args = arguments,
            curTime = new Date();

        clearTimeout(timeout);
        // 如果達到了規定的觸發時間間隔,觸發 handler
if(curTime - startTime >= mustRun){ func.apply(context,args); startTime = curTime; // 沒達到觸發間隔,重新設定定時器 }else{ timeout = setTimeout(func, wait); } }; }; // 實際想繫結在 scroll 事件上的 handler function realFunc(){ console.log("Success"); } // 採用了節流函式
window.addEventListener('scroll',throttle(realFunc,500,1000));