smotru smotru - 2 months ago 9
Javascript Question

How to use setInterval with random number of miliseconds each time?

The function

showRandom
is executed every 1000 miliseconds but i want it to be executed every
random
miliseconds.. 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

Answer

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
}