我见过很多示例,但没有一个能够完全满足需要。这似乎是最接近的,但使用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()来代替,但我不明白如何使它做我需要的。
你没有清除间隔,所以它看起来不稳定,但它真的只是将所有未清除的间隔堆叠在一起。 –