2017-03-21 66 views
0

當我運行此代碼時,在控制檯中看不到任何控制檯日誌。反彈方法(取自here)根本不執行該方法嗎?爲什麼不執行debounce函數執行該方法?

function debounce(func, wait, immediate) { 
 
    var timeout; 
 
    var args = Array.prototype.slice.call(arguments, 3); 
 
    return function() { 
 
     var context = this; 
 
     var callNow = immediate && !timeout; 
 
     clearTimeout(timeout); 
 
     timeout = setTimeout(function() { 
 
      timeout = null; 
 
      if (!immediate) { 
 
       func.apply(context, args); 
 
      } 
 
     }, wait); 
 
     if (callNow) func.apply(context, args); 
 
    }; 
 
}; 
 

 
var f1 = function(){ console.log(1) }; 
 
var f2 = function(){ console.log(2) }; 
 
debounce(f1, 100, false); 
 
debounce(f2, 100, false);

這是預期的行爲,還是我錯過了什麼嗎?

回答

1

這是因爲你的debounce函數返回另一個函數。你要這樣稱呼它:

debounce(f1, 100, false)(); 
debounce(f2, 100, false)(); 

function debounce(func, wait, immediate) { 
 
    var timeout; 
 
    var args = Array.prototype.slice.call(arguments, 3); 
 
    return function() { 
 
     var context = this; 
 
     var callNow = immediate && !timeout; 
 
     clearTimeout(timeout); 
 
     timeout = setTimeout(function() { 
 
      timeout = null; 
 
      if (!immediate) { 
 
       func.apply(context, args); 
 
      } 
 
     }, wait); 
 
     if (callNow) func.apply(context, args); 
 
    }; 
 
}; 
 

 
var f1 = function(){ console.log(1) }; 
 
var f2 = function(){ console.log(2) }; 
 
debounce(f1, 100, false)(); 
 
debounce(f2, 100, false)();

+0

謝謝,這有助於。不能相信我錯過了:) – gurvinder372

相關問題