2017-02-13 31 views
2

讓我知道設置clearTimeout和將相同變量設置爲null用於設置settimeout的id之間的區別。設置clearTimeOut

我在下面提到的underscore.js中看到了一個函數。

function debounce(func, wait, immediate) { 
    var timeout, args, context, timestamp, result; 

    var later = function() { 
     var last = new Date().getTime() - timestamp; 

     if (last < wait && last >= 0) { 
      timeout = setTimeout(later, wait - last); 
     } else { 
      timeout = null; 
      if (!immediate) { 
       result = func.apply(context, args); 
       if (!timeout) context = args = null; 
      } 
     } 
    }; 

    return function() { 
     context = this; 
     args = arguments; 
     timestamp = new Date().getTime(); 
     var callNow = immediate && !timeout; 
     if (!timeout) timeout = setTimeout(later, wait); 
     if (callNow) { 
      result = func.apply(context, args); 
      context = args = null; 
     } 

     return result; 
    }; 
}; 

它最終將「timeout」變量設置爲「null」而不是使用clearTimeOut。

回答

1

clearTimeout如果尚未運行,實際上會取消預定功能。所以當它。

當預定時間在當前時間之前,這段代碼將timeout設置爲null,因此它將其設置爲null以清除該值,以便其他代碼知道沒有超時等待。 因爲這段代碼不需要取消超時,所以它不使用clearTimeout

基本上,clearTimeout和unsetting變量沒有任何關係。

+0

感謝您接受我的回答,這不是很清楚,所以如果任何社區成員想要編輯它,請隨時取消。 – PaulBGD