2016-04-15 31 views
-4

好吧,我得到了這個<button onclick="alert('1');setInterval(function(){},57000);alert('2');"> Show </button>有沒有一個Javascript函數來讓代碼在運行時延遲?

延遲沒有奏效。

setTimeout也沒有工作。

如何解決?

+1

'function(){}'< - 但它什麼都不做。 –

+1

可能重複的[在JavaScript中的兩行代碼之間的時間延遲,而不是settimeout](http://stackoverflow.com/questions/3048724/time-delay-between-2-lines-of-code-in-javascript-not -settimeout) –

回答

4

把警報的setInterval回調中:

<button onclick="alert('1');setInterval(function(){alert('2');},57000);"> Show </button> 

簡單的擴展版本的代碼:

var div = document.querySelector('div'); 
 

 
function myFunction(){ 
 
    div.textContent += '-'; 
 
    // beware, this code might crash your browser if left running 
 
    // for a few (thousand) years!!! 
 
}
<button onclick="setInterval(myFunction, 1000);"> Start Interval </button> 
 
<div></div>


一個正確風格以上代碼的版本:

var div = document.getElementById('d'); 
 
var button = document.getElementById('b'); 
 

 
button.addEventListener('click', clickHandler); 
 

 
function myFunction(){ 
 
    div.textContent += '-'; 
 
    // beware, this code might crash your browser if left running 
 
    // for a few (thousand) years!!! 
 
} 
 

 
function clickHandler(){ 
 
    setInterval(myFunction, 1000); 
 
}
<button id="b"> Start Interval </button> 
 
<div id="d"></div>

+0

有沒有辦法做到這一點。讓代碼獨立 – Tum

+0

您可以將所有其他代碼放在一個函數中,然後將該函數作爲參數傳遞給'setInterval':'setInterval(myFunction,57000);' – Shomz

+0

請注意,這將每57年提醒「2」秒。沒有任何反對的答案,只爲那些尋找延遲而不是重複呼叫的人。 –

0

JavaScript代碼運行同步,這意味着每個指令被執行一個之後。讓我們來看看你的代碼:

alert('1'); 

setInterval(function(){ 
    //does nothing 
}, 57000); 

alert('2'); 

現在每個行會其他,這意味着alert(1)會執行,然後setInterval(...)然後alert(2)後執行一個。您的setInterval不是停止其他行執行。

如果你想對你的代碼執行的延遲,你必須考慮具有代碼執行你setInterval(我假設你想在這裏使用setTimeout)結束

此外,作爲專業人士,您應該將您的JavaScript代碼從HTML中分離出來。讓我們考慮以下內容:

<button id="myButton">Show</button> 
... 
<script> 
// Get a reference to your button 
var myButton = document.querySelector('#myButton'); 

// The code you want to execute after the given time 
function executeLater(){ 
    alert(2); 
} 

// We attach an event listener to your button 
myButton.addEventListener('click', function(){ 
    alert('1'); 
    setTimeout(executeLater, 2000); 
}); 
</script> 
+0

如果你不把alert('2')放在myFunction中?如果你這樣做,它不會延遲 – Tum

+0

@tum你必須理解JavaScript的同步性 - 只需單獨設置一個setTimeout或setInterval在它之後不會阻塞代碼,所以如果你希望代碼在以後執行,你必須使用回調 –