Friday, May 17, 2024
 Popular · Latest · Hot · Upcoming
154
rated 0 times [  159] [ 5]  / answers: 1 / hits: 16344  / 8 Years ago, tue, february 16, 2016, 12:00:00

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>




More From » jquery

 Answers
7

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>




[#63293] Sunday, February 14, 2016, 8 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
mustafaericho

Total Points: 322
Total Questions: 103
Total Answers: 110

Location: Montenegro
Member since Thu, Jun 16, 2022
2 Years ago
mustafaericho questions
Mon, May 31, 21, 00:00, 3 Years ago
Sun, May 23, 21, 00:00, 3 Years ago
Sat, Feb 13, 21, 00:00, 3 Years ago
Sat, Jan 2, 21, 00:00, 3 Years ago
Thu, Nov 12, 20, 00:00, 4 Years ago
;