How to use setInterval with random number of milliseconds each time?
javascript, random, setinterval
Solution
Felix said it: If you want to change the interval every time, use `setTimeout` instead. Simplified example as I'm having trouble following exactly what you want your original code to do:
doTheRandom();
function doTheRandom() {
random = randomizator(60000,200000);
// Up to 1 second
setTimeout(doTheRandom, randomizator(1000, 2000)); // 1-2 seconds
}
Problem
The function `showRandom` is executed every 1000 milliseconds but i want it to be executed every `random` milliseconds.. is there any solution for this ? Thank you! ``` var random = 1000; setInterval(function() {random = randomizator(60000,200000);} ,1000); setInterval(function() {showRandom(random);}, random); function randomizator(a,b) { return Math.floor(Math.random()*b) + a; } function showRandom(random) { $('#test').text(random); } ``` DEMO: jsFiddle