2016-08-03 97 views
0

answers to this question有人明智地指出,爲什麼在這種情況下超時變量可共享?

超時變量保持甚至抖本身已經返回後 生產函數的每一個電話期間訪問,並且可以在不同的呼叫 變化。

這對我來說並不合適。由於超時變量對於每次去抖動調用都是本地的,因此它不應該是可共享的,不是嗎?

p.s.即使它是關閉的,每個調用應該有不同的關閉,它們同時都是在母函數返回後延長他們的生命,但它們不應該彼此交談,對嗎?

下面是其他問題的功能:

// Returns a function, that, as long as it continues to be invoked, will not 
// be triggered. The function will be called after it stops being called for 
// N milliseconds. 
function debounce(func, wait, immediate) { 
    var timeout;    //Why is this set to nothing? 
    return function() { 
     var context = this, 
     args = arguments; 
     clearTimeout(timeout); // If timeout was just set to nothing, what can be cleared? 
     timeout = setTimeout(function() { 
      timeout = null; 
      if (!immediate) func.apply(context, args); 
     }, wait); 
     if (immediate && !timeout) func.apply(context, args); //This applies the original function to the context and to these arguments? 
    }; 
}; 

回答

2

是的,debounce每次通話將獲得一套全新的一切,但是你是不是重複調用debounce。您正在呼叫debounce一次,然後重複呼叫從debounce返回的功能。該功能關閉timeout

var f = debounce(func, wait, immediate); 
f(); // won't call func immediately 
f(); // still won't call func 
// wait a while, now func will be called 

你只叫debounce本身多次設置多個抖功能(在上面的示例中gh)。

+0

優秀的答案!恰到好處。謝謝你Thilo! –

+1

「上下文」變量是否有實際用途?在我的調試測試中,「context」變量總是指向Window對象。我想這是因爲它是一個匿名函數。它可以用於其他用途嗎?謝謝。 –

+1

我想你可以將返回的閉包分配給一個對象,並且該對象將在原始的'func'中變成'this':var x = {f:debounce(func,w,i)}; x.f(); }' – Thilo

相關問題