我見過很多示例,但沒有一個能夠完全滿足需要。這似乎是最接近的,但使用setTimeout,並不是我需要做的。 Change setInterval value dynamically動態更改setInterval值作爲其運行
我有一個下拉/選擇,使用戶可以選擇更新時間,5秒,10秒和60秒以及一起停止刷新。
<select id="refTime" name="refTime" size="7" onchange="chngAutoRef();">
<option value="60">Time to refresh </option>
<option value="0"> No Auto Refresh </option>
<option value="5"> 5 seconds </option>
<option value="10"> 10 seconds </option>
<option value="20"> 20 seconds </option>
<option value="30"> 30 seconds </option>
<option value="60"> 60 (default) </option>
</select>
而我正在使用javascript。
var interval = 60;
function chngAutoRef() {
clearInterval(autoRefId);
var autoRefId = null;
var interval = $('#refTime').find(":selected").val();
var newButton = "every " + interval;
$("#refbutton").attr('value',newButton); // rename the ref button
if (typeof interval == 'undefined') {interval = 60;}
if (autoRefId !== null) {
$("#autoref").html('Start Auto Ref'); // You see this if Refresh is not automatically happening
clearInterval(autoRefId);
autoRefId = null;
} else {
interval = interval * 1000;
$("#autoref").html('Stop Auto Ref'); // You see this if Refresh is automatically happening
autoRefId = setInterval(function() {
showActivities(document.getElementById("select1").value);}, interval);
}
} // end of function chngAutoRef()
chngAutoRef();
當頁面啓動時,默認值爲60秒,如果用戶選擇5秒,則每5秒刷新一次。但是,如果用戶然後將選擇更改爲10秒(或任何其他),則刷新變得不穩定並且更新5或10或1秒(除了所請求的10之外的任何內容)。
我試過使用setTimeout()來代替,但我不明白如何使它做我需要的。
你沒有清除間隔,所以它看起來不穩定,但它真的只是將所有未清除的間隔堆疊在一起。 –