2017-08-02 190 views
-4

我是這個部門的新手,所以我想知道,我可以製作一種類型的if語句嗎?例如:如果某個動作(可能是點擊事件)在一段時間內完成,則時間被重置,如果沒有,則調用一個函數。JavaScript時間延遲

+0

絕對!你正在尋找[**'setTimeout()'**](https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/setTimeout),或者最好是[**回調**](http://javascriptissexy.com/understand-javascript-callback-functions-and-use-them/)。 –

+0

請參閱** ['setTimeout()'](https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/setTimeout)**。 –

回答

0

您不能使用if聲明來做到這一點,但您可以使用setTimeoutclearTimeout

下面是一個示例,說明只要不單擊按鈕,您可以每2秒運行一個函數(console.log語句)。點擊按鈕重置計時器,以便在再次開始記錄之前需要等待另外2秒。你可以適應這種情況,以適應你需要發生的任何實際工作。

var currentTimeoutId; 
 
function resetTimeout() { 
 
    clearTimeout(currentTimeoutId); 
 
    currentTimeoutId = setTimeout(function() { 
 
    console.log('Too Late!'); 
 
    resetTimeout(); 
 
    }, 2000); 
 
} 
 

 
resetTimeout(); 
 
document.getElementById('demo').onclick = function() { 
 
    resetTimeout(); 
 
};
<button id="demo">Click Me Or Else I'll Log Something!</button>

+0

謝謝!我正在嘗試setTimeout(),但我無法弄清楚如何正確使用它。謝謝! –