Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
770 views
in Technique[技术] by (71.8m points)

javascript - 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>
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...