Reputation: 431
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
Upvotes: 5
Views: 9967
Reputation: 93363
Since the implementation of setInterval(fn,PERIOD)
using setTimeout
is :
setTimeout(fn,iteration*PERIOD) // iteration ∈ [1,2,3...,n]
So ,what you need is to use setTimeout
, with randomizing iteration*PERIOD
Upvotes: 0
Reputation: 3665
If you want a random interval you could use setTimeout instead. Heres an example to give you an idea (not tested could contain errors):
function setRandomInterval(){
//Add your code here
setTimeout(function(){
setRandomInterval();
}, Math.random()*1000);
}
The problem with setInterval is, that once you've setted it the interval is fixed. You could stop the interval and start a new one but setTimeout will be the better solution.
Upvotes: 0
Reputation: 17767
setInterval(function() {
//your code to be executed every random miliseconds
} ,random_interval());
var random_interval=function(){
return Math.random()*1000;
}
Upvotes: 1
Reputation: 1075079
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
}
Upvotes: 5