点击按钮后,我需要更新setIntreval的时间。
var seconds = 5;
<input id="new-time" />
<button id="new-time-submit">submit</button>
$("#new-time-submit").on("click", function(){
seconds = $("#new-time").val();
});
setInterval(function(){
alert(seconds);
// my codes
}, seconds*1000);
运行setInterval时,它会发出新值警报,但像以前一样每5秒重复一次。 如何更改setInterval持续时间中的秒值?
答案 0 :(得分:2)
您需要将setInterval存储在变量中,然后单击按钮以清除先前的setInterval值,然后再次使用新的计时器值触发setInterval。
var setIIntervalFlag;
$("#new-time-submit").on("click", function(){
startSetInterval($("#new-time").val()); //On Button Click
});
startSetInterval = (seconds) => {
if(setIIntervalFlag){
clearInterval(setIIntervalFlag) //Clear previous setInterval if exists
}
//start setInterval and store the value
setIIntervalFlag = setInterval(function(){
alert(seconds);
// codes
}, seconds*1000);
}
startSetInterval(5) // on page Load
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input id="new-time" />
<button id="new-time-submit">submit</button>