0

I need to update the time of setIntreval after clicking the button.

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);

When the setInterval runs, it alerts new value but it repeats every 5 seconds as before. How can I chage the seconds value in setInterval time duration?

Atousa Darabi
  • 847
  • 1
  • 7
  • 26

1 Answers1

2

You need to store your setInterval in a variable and on click of button clear your previous setInterval value and again trigger setInterval with new timer value.

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>
Ashish
  • 4,206
  • 16
  • 45