Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to change the interval dynamically when using setInterval

I have this fiddle : https://jsfiddle.net/reko91/stfnzoo4/

Im currently using Javascripts setInterval() to log a string to console.

What I want to do, is in this setInterval function check whether the interval variable has changed, if it has, change the interval in the setInterval function. I can lower the interval variable by 100 (speeding the function up) by a click a button.

Is this possible ?

Someone mentioned this : Changing the interval of SetInterval while it's running

But this is using a counter, so they only run it a certain amount of times. I need to run it for however long, but change how fast the function gets called again.

Here is the code :

var interval = 2000;

setInterval(function() {
  interval = getInterval();
  console.log('interval')
}, interval);


function getInterval() {
  return interval;
}


$('#speedUp').on('click', function() {
  interval -= 100;
  console.log(interval)
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id='speedUp'>
  speed up
</button>
like image 902
thatOneGuy Avatar asked Feb 16 '16 20:02

thatOneGuy


1 Answers

I would just stop the interval and start a new one with the different timing

var interval = 2000;
var intervalId;

// store in a function so we can call it again
function startInterval(_interval) {
  // Store the id of the interval so we can clear it later
  intervalId = setInterval(function() {
    console.log(_interval);
  }, _interval);
}


function getInterval() {
  return interval;
}


$('#speedUp').on('click', function() {
  interval -= 100;
  // clear the existing interval
  clearInterval(intervalId);
  // just start a new one
  startInterval(interval);
  console.log(interval)
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id='speedUp'>
  speed up
</button>
like image 187
Dustin Stiles Avatar answered Oct 06 '22 00:10

Dustin Stiles